PHP: Get list of all filenames contained within my images directory
Listing files in a directory is one of those tasks that feels trivial until you actually try to implement it, only to discover how many edge cases exist between reading the filesystem and getting a clean array of filenames. The core mechanism relies on the opendir, readdir, and closedir functions, but the devil is often in the details: handling hidden files, dealing with permission errors, and deciding whether you want subdirectories included or excluded.
If your goal is simply to grab every file sitting directly inside an "images" folder, you don't need a complex recursive walker yet. You can start with a straightforward implementation using scandir. This function returns all entries in the directory, including hidden files and directories, which is usually exactly what you want when scanning for assets.
$directory = '/path/to/images';
$files = scandir($directory);
// Filter out the two special entries '.' and '..' which always appear first
$files = array_diff($files, ['.', '..']);
// Optionally filter by extension to ensure you only get images
$imageExtensions = ['jpg', 'jpeg', 'png', 'gif', 'webp'];
$imageFiles = [];
foreach ($files as $file) {
if (is_file($file) && in_array(strtolower(pathinfo($file, PATHINFO_EXTENSION)), $imageExtensions)) {
$imageFiles[] = $file;
}
}
This approach gives you immediate control over what gets included. By checking is_file(), you explicitly exclude subdirectories from the list. If you omit that check, your array will be polluted with folder names like thumbnails or cached, which can break downstream logic if you assume every entry is a valid asset.
Handling Hidden Files and Permissions
A common pitfall occurs when dealing with hidden files. By default, scandir includes dotfiles (files starting with a dot). In an images directory, this might be acceptable if you store metadata or thumbnails with names like .last_modified. However, if your application expects only standard image assets, you need to filter them out manually using substr($file, 0, 1) !== '.'.
Another critical consideration is permission errors. If the web server user lacks read permissions on the directory, scandir will throw a warning and return an array containing only the current directory and parent directory entries (or empty, depending on the PHP version). To handle this robustly, you should wrap the logic in a try-catch block or check for errors specifically if your application environment is production-grade.
if (!is_readable($directory)) {
throw new InvalidArgumentException("Directory $directory is not readable.");
}
Recursive Scanning with RecursiveDirectoryIterator
Once you need to dig deeper, simply scanning the root directory isn't enough. You might need a list of every image file nested several levels deep, perhaps in an images/photos/2023 structure. For this scenario, switching to RecursiveDirectoryIterator combined with RecursiveIteratorIterator is the standard pattern. This allows you to iterate through directories without writing your own recursion logic.
$iterator = new RecursiveIteratorIterator(
new RecursiveDirectoryIterator($directory)
);
$imageFiles = [];
foreach ($iterator as $file) {
if ($file->isFile()) {
// Apply extension filter here
$extension = strtolower(pathinfo($file->getPathname(), PATHINFO_EXTENSION));
if (in_array($extension, ['jpg', 'png', 'gif'])) {
$imageFiles[] = $file->getBasename();
}
}
}
The trade-off here is performance and complexity. RecursiveDirectoryIterator can be memory-intensive on very large directory trees compared to a simple loop with scandir. If you are processing millions of files, you might need to batch the results or use streaming iterators to keep memory usage low. Additionally, ensure that the path resolution is consistent; using $file->getPathname() resolves symlinks and provides an absolute path, whereas $file->getBasename() gives just the filename without directory context.
For developers working within the Laravel ecosystem, the Illuminate\Filesystem\Filesystem facade often simplifies these operations by abstracting away the iterator patterns into helper methods like filesInDirectory, which handles some of the boilerplate for you. However, understanding the underlying mechanics remains essential when custom filtering logic is required.