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:

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:

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 Reply