Sunday, March 5, 2023

trivial php directory of images to image gallery

 I feel like I must have written this already half a dozen times, but I couldn't find quite the equivalent posted here: a trivial script to dump every file that looks like an image based on extension into an img tag, with a link/filename before it.


<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<style>
body {
    font-family: sans-serif;    
    margin: 80px;
    font-size:24px;
}
img {
 width: 100%;   
}

</style>
</head>
<body>

<? $files = array_values(array_diff(scandir('.'), array('.', '..')));

$imageendings = array(".jpg",".jpeg",".png",".gif",".webp", ".svg");
foreach ($files as $file) {
        $lowercaseFile = strtolower($file);
       if(endsWithOneOf($lowercaseFile,$imageendings)) {
            print "<p>";
            print "<a href='$file'>$file</a><br>";
            print "<img src='$file'>";
            print "</p>";
       } 
}
function endsWithOneOf($haystack, $needles){
    foreach($needles as $needle) {
        if(endsWith($haystack, $needle)) return true;   
    }
    return false;
}

function endsWith($haystack, $needle) {
    $length = strlen($needle);
    return $length === 0 || 
    (substr($haystack, -$length) === $needle);
}


?>
</body>
</html>

No comments:

Post a Comment