Using GLOB to retrieve the filtered contents of a directory

I am not a demanding man.

I have a directory of images; I want a list of the images inside.

The usual drill is to create a directory handle and loop through, returning everything that’s found, then close the handle, like so:

<?php
$dir = "/var/www/vhosts/example.com/images/";
$handle = opendir($dir);
while (false !== ($file = readdir($handle))) {
    echo $file;
}
closedir($handle);
?>

Here’s our output:

.
..
.DS_Store
.svn
001.jpg
002.jpg
003.jpg

Hmm. In addition to our images our code has returned a bunch of other stuff — UNIX shorthand for the current and parent directories, an annoying .DS_Store file, and a Subversion directory — so clearly we need to add a little filtering:

<?php
$dir = "/var/www/vhosts/example.com/images/"
$handle = opendir($dir);
while (false !== ($file = readdir($handle))) {
    if (strpos($file, ".jpg") !== false) {
        echo $file;
    }
}
?>

Now, with glob(), we can do exactly the same thing, but a whole lot neater:

<?php
$dir = "/var/www/vhosts/example.com/images/";
foreach (glob($dir."*.jpg" as $file)) {
   echo $file;
}
?>

No creating directory handles, no separate filtering, and no having to remember to close anything. Plus the image names are returned with absolute paths, so if you need to compile size information you can do so with right inside the loop.

That, and it’s one letter off from G.O.B. — Come on!