Other Ways to List Files with PHP

As we touched on with this blog post, we were listing files with he DirectoryIterator object, which gives us an SPLFileObject. This method is excellent for situations when you want to know the details of every file in the folder. However, if you're looking to grab specific files or extensions and don't care too much about the details of each file, it's much more efficient to use the glob() function or scandir(), which return a list of files as an array.

// list just text files
foreach (glob("./myfolder/*.txt") as $filename) {
echo "$filename size " . filesize($filename) . "<br />";
}

If you want to exclude files, you could use scandir() and array_diff()

// exclude dot files and .DS_Store
$excludes = array('.', '..', '.DS_Store');
$files = array_diff(scandir('./files/img'), array('.', '..'));
foreach($files as $filename) {
echo "$filename size " . filesize($filename) . "<br />";
}

Now, if you wanted to include only certain extensions, you could do:

$files = scandir('./images/');
$allow_extensions = array('jpg', 'png', 'gif');
foreach($files as $filename) {
$file_parts = pathinfo($filename);
if (in_array($file_parts['extension'], $allow_extensions)) {
echo "$filename size " . filesize($filename) . "<br />";
}
}