How to use PHP’s glob function to list files by their extension

There comes a time when you need to list files in a directory, but you only want certain files by extension. Here’s how you do that:

$files = glob('/your-path/your-directory/*.{png,gif,jpg,jpeg}', GLOB_BRACE);
if(count($files) > 0) {
foreach($files as $file) {
// DO SOMETHING HERE
}
}

The previous example will list all the images with extensions png, gif, jpg or jpeg. This works fine for the most part, but what if someone is a jerk and forgets the extension, or maybe they had the extension capitalized? Well, if it’s capitalized, you can just add that to the brackets, but if there isn’t an extension, then you’re going to have to do something like this:

$files = array_filter(glob("/your-path/your-directory/*"), 'is_file');
// keep in mind that array_filter will preserve the array keys. 
if(count($files) > 0) {
$finfo = finfo_open(FILEINFO_MIME_TYPE);
foreach($files as $file) {
if(in_array(finfo_file($finfo, $file), array('image/jpeg', 'image/gif', 'image/png'))) {
// DO SOMETHING
}
}
finfo_close($finfo);
}

That will list all the images in the directory, regardless of extension, but only the types of files that you want to work with. Why would you want to do this? I don’t ask these questions.

Leave a comment

Find the Best SEO in Fort Lauderdale, Florida (Plantation SEO) | Drupal & Worpress Develpment