Loop code for each file in a directory

Loop code for each file in a directory

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

Stefan Bogdanescu

Founder & Senior Architect

Looping Through Directory Files in PHP

When you need to process a collection of images or other assets stored on disk, the immediate instinct is often to grab a simple list and iterate over it. In PHP, this usually starts with scandir() or glob(). While these functions return arrays of filenames, relying solely on them introduces significant friction when dealing with subdirectories, hidden files, or cases where you need full path information. The most robust approach involves the DirectoryIterator class, which provides an iterator interface specifically designed for traversing file system hierarchies.

Using DirectoryIterator allows you to iterate over entries without manually managing array indices. You can check if a specific entry is a regular file using the isFile() method before attempting to read or calculate anything on it. This prevents runtime errors that occur when trying to perform file operations on directories themselves. Here is a standard pattern for iterating through files in a single directory:

$dir = new DirectoryIterator('/path/to/your/directory');

foreach ($dir as $fileInfo) {
    if ($fileInfo->isFile()) {
        // Process only regular files, skipping subdirectories
        $filename = $fileInfo->getBasename();
        
        // Example calculation: get file size in bytes
        $sizeInBytes = $fileInfo->getSize();
        
        // Perform your logic here
        echo "Processing: $filename ({$sizeInBytes} bytes)\n";
    }
}

This approach automatically handles the directory traversal logic. The iterator yields each entry one by one, and the isFile() check acts as a filter to ensure you only operate on actual files. If your goal is to calculate totals, such as the aggregate size of all images in a folder, accumulating the values inside the loop is efficient and memory-safe.

However, there are scenarios where DirectoryIterator might not be the only tool in your toolbox. The older opendir() function paired with readdir() offers a similar iterative experience but feels more procedural and verbose compared to the object-oriented nature of DirectoryIterator. Unless you have a specific legacy constraint or need to manipulate directory handles directly, DirectoryIterator remains the preferred standard for modern PHP applications.

If your project relies on Laravel, the ecosystem provides a convenient facade to interact with file systems without writing raw iterator logic from scratch. The Storage facade wraps these low-level operations and allows you to list files within a specific disk path using the all() method. This is particularly useful if your images are stored on S3 or other remote storage backends rather than local disk space.

use Illuminate\Support\Facades\Storage;

$files = Storage::disk('public')->allFiles('/images');

foreach ($files as $file) {
    // Logic for remote or local files handled by Laravel's abstraction
    if (Storage::exists($file)) {
        $size = Storage::size($file);
        // Process $file
    }
}

While the allFiles() method is convenient, be aware that it loads the entire list of files into memory before returning. If you are working with a directory containing hundreds of thousands of files, iterating directly via DirectoryIterator or using the cursor() method in Laravel (available in newer versions) might offer better performance characteristics by processing items lazily.

When performing file calculations, always validate that the file exists and is readable before attempting to access its metadata or contents. A simple isReadable() check on the DirectoryIterator object can prevent permission errors that halt execution unexpectedly. Additionally, remember that filenames returned by these methods do not include the directory path unless you explicitly request it using getPathname(). This distinction is crucial if your calculation logic depends on knowing the full absolute location of the asset.

Our network