PHP DirectoryIterator: How to Iterate Over a Directory

This article provides a straightforward guide on how to use PHP’s built-in DirectoryIterator class to loop through files and folders in a directory. You will learn how to initialize the class, filter out parent and current directory pointers, and retrieve file properties like names, paths, and sizes using standard object-oriented methods.

The DirectoryIterator class is part of PHP’s Standard PHP Library (SPL). It provides a simple, object-oriented interface for viewing the contents of a filesystem directory. Unlike older functions like readdir(), DirectoryIterator allows you to iterate through a directory using a standard foreach loop and retrieve detailed file information through dedicated object methods.

Basic Usage Example

To iterate over a directory, instantiate the DirectoryIterator class with the path to the target directory, and then loop through the object using foreach.

<?php
$directoryPath = '/path/to/directory';

try {
    $dir = new DirectoryIterator($directoryPath);

    foreach ($dir as $fileinfo) {
        // Skip the '.' and '..' directories
        if (!$fileinfo->isDot()) {
            echo $fileinfo->getFilename() . "\n";
        }
    }
} catch (UnexpectedValueException $e) {
    echo "Error: The directory could not be opened. " . $e->getMessage();
} catch (RuntimeException $e) {
    echo "Error: " . $e->getMessage();
}

Key Methods of DirectoryIterator

During each iteration of the loop, the $fileinfo variable represents the current DirectoryIterator object, positioned at the current file or folder. You can use several built-in methods to gather information about the item:

Filtering Files by Type

You can combine these methods to target specific types of items within your directory structure. For example, if you want to display only files (excluding subdirectories):

foreach ($dir as $fileinfo) {
    if ($fileinfo->isFile()) {
        echo "File: " . $fileinfo->getFilename() . " (" . $fileinfo->getSize() . " bytes)\n";
    }
}

Using DirectoryIterator is highly recommended because it is memory-efficient, readable, and handles directory traversal securely using native PHP exceptions when a directory does not exist or lacks permissions.