Recursive Directory Listing in PHP: A Practical Guide
Listing files within a single directory is trivial using scandir() or glob(). However, developers frequently encounter scenarios where they need to aggregate every file across an entire directory tree, including nested sub-directories. The requirement often boils down to returning a flat array of filenames, regardless of their depth in the hierarchy.
To achieve this, you have two primary architectural choices: leveraging built-in standard library functions or utilizing dedicated recursion helpers like RecursiveDirectoryIterator. Each approach carries distinct trade-offs regarding performance, readability, and edge-case handling.
Using RecursiveDirectoryIterator
The most robust and modern solution relies on PHP's RecursiveDirectoryIterator class combined with RecursiveIteratorIterator. This pattern abstracts away the complexity of manually walking the directory tree.
First, instantiate a RecursiveDirectoryIterator for the target folder. Then, wrap it with a RecursiveIteratorIterator set to traverse all levels. Finally, filter the results to exclude directories and keep only files.
$directory = 'foldername';
try {
$iterator = new RecursiveDirectoryIterator($directory);
// Flatten the recursion so we can iterate linearly
$flatIterator = new RecursiveIteratorIterator($iterator);
$files = [];
foreach ($flatIterator as $file) {
// Ensure we skip directories and only process files
if ($file->isDir()) {
continue;
}
$files[] = $file->getFilename();
}
} catch (Exception $e) {
// Handle permission errors or non-existent paths gracefully
return [];
}
// Result: array("file.jpg", "blah.word", "name.fileext")
This approach is preferred when dealing with large directory structures because it efficiently manages the file handle context. It also naturally handles permission issues by throwing exceptions that can be caught and logged, preventing silent failures.
The Recursive scandir() Approach
For those who prefer a procedural style or are working within an older codebase, you can implement a recursive function using scandir(). This method involves calling the function on the current directory, then iterating through each result to call itself if the entry is a directory.
function listAllFiles($path) {
$files = [];
// Check if the path exists and is readable
if (!is_dir($path)) {
return $files;
}
$items = scandir($path);
foreach ($items as $item) {
// Skip . and .. entries
if ($item === '.' || $item === '..') {
continue;
}
$fullPath = rtrim($path, DIRECTORY_SEPARATOR) . DIRECTORY_SEPARATOR . $item;
if (is_dir($fullPath)) {
// Recursively call for subdirectories
$files = array_merge($files, listAllFiles($fullPath));
} else {
$files[] = $item;
}
}
return $files;
}
While functional, this recursive implementation has a notable limitation: it does not handle deep nesting well if the recursion depth exceeds the system's stack limit. Additionally, scandir() returns dot files (like .git or .env) by default, which you must explicitly filter out to avoid polluting your file list with hidden configuration artifacts.
Performance and Edge Cases
When choosing between these methods, consider the context of your application. If you are scanning a massive project repository, the RecursiveDirectoryIterator approach is generally more memory-efficient because it processes items in a stream-like fashion rather than building up a full tree structure in memory before flattening.
Be wary of infinite loops if your directory structure contains symbolic links pointing back to parent directories. Both methods above naturally handle symlinks by resolving them into their target paths, but you may need to add specific logic if you want to preserve the symlink path instead of the resolved file path. Always validate that the input directory exists and is readable before attempting to scan it to prevent fatal errors in production environments.