Quickly display all images within a directory with PHP
<?php
// Define which directory to use
$dir = 'images';
// Filter out wanted file suffixes
$file_display = array('jpg', 'jpeg', 'png', 'gif');
if(file_exists($dir) == false){
// If there isn't a directory by that name
echo 'Directory \'', $dir, '\' not found!';
} else{
// Scan through the directory
$dir_contents = scandir($dir);
foreach ($dir_contents as $file){
// Fix so that even uppercase suffixes works
$file_type = strtolower(end(explode('.', $file)));
if ($file !== '.' && $file !== '..' && in_array($file_type, $file_display) == true){
// Wrap each file within a img tag
echo '<img src="', $dir, '/', $file, '" alt="', $file, '" />';
}
}
}
?>
I'm building a photo gallery, where just putting images in a directory would display them nicely on a page.