PHP read sub-directories and loop through files how to?

PHP read sub-directories and loop through files how to?

  1. Blog
  2. 15 November 2026
  3. 3 min read

Stefan Bogdanescu

Founder & Senior Architect

Recursive Directory Traversal in PHP

The core challenge you are facing is a classic traversal problem: iterating over every file within a directory tree without writing your own recursive function. While manual recursion is possible, it introduces stack depth risks and repetitive code patterns that are easily solved using built-in standard library functions. The most robust approach relies on RecursiveDirectoryIterator combined with RecursiveIteratorIterator.

This combination allows you to flatten the directory structure into a single stream of paths, effectively handling nested subdirectories automatically. You do not need to manually implement the "loop through sub-directories" logic; the iterator handles the depth-first search internally.

Here is how you structure the code to achieve the desired behavior:

$main = 'MainDirectory';

try {
    $directoryIterator = new RecursiveDirectoryIterator($main);
    
    // Wrap the directory iterator in a recursive iterator to flatten the tree
    $flatIterator = new RecursiveIteratorIterator($directoryIterator);
    
    foreach ($flatIterator as $file) {
        if ($file->isDir()) {
            continue;
        }

        $path = $file->getPathname();
        
        // do something with each file
        echo "Processing: " . $path . PHP_EOL;
    }
} catch (Exception $e) {
    // Handle potential permission errors or missing directories
    error_log("Error traversing directory: " . $e->getMessage());
}

The logic here is straightforward. First, RecursiveDirectoryIterator scans the root folder (MainDirectory). It returns entries for files and subdirectories at all levels. The second iterator, RecursiveIteratorIterator, walks through those results and yields them one by one as if it were a flat list. This mimics the nested loop structure you requested but with significantly less boilerplate.

Handling Permissions and Symlinks

A critical pitfall in directory traversal is handling permission errors or symbolic links. The standard iterator will throw exceptions if a subdirectory is unreadable or if a symlink points to a location without read access. Wrapping the logic in a try-catch block, as shown above, is essential for production stability. You should catch UnexpectedValueException specifically, which is the parent class for most filesystem-related errors in this context.

Additionally, be mindful of symbolic links. If your directory tree contains circular symlinks (e.g., dir1 -> dir2 -> dir1), the iterator will enter an infinite loop or exhaust memory depending on the PHP version and configuration. The built-in iterators generally handle cycles gracefully by following them, but in rare cases involving deeply nested self-referential links, you may need to implement a visited set or rely on RecursiveDirectoryIterator's default behavior which typically avoids re-processing entries it has already seen in the current stack.

Using Laravel for Directory Operations

If you are working within a Laravel application, the native PHP classes remain the most efficient tool for this specific task because they operate at the filesystem level rather than the ORM or Eloquent layer. However, if your goal involves processing files that map directly to database records or need to trigger events upon discovery, you might consider integrating this logic into an Artisan command.

For example, you could create a custom console command that utilizes this iterator pattern and emits progress bars or sends notifications when specific file types are found. This keeps your application logic clean and adheres to Laravel's service-oriented architecture. For more complex directory scanning needs within the framework ecosystem, resources like https://laravelcompany.com often provide deeper insights into leveraging filesystem events or optimizing batch processing tasks.

Ultimately, using RecursiveIteratorIterator is the industry-standard solution for this problem. It decouples the traversal logic from your business logic, allowing you to focus entirely on "doing something with each file" without worrying about directory depth or structure.

Our network