Before and After: Recursive Directory Iteration

The previous iterator examples handle only a flat list of items, but frequently your lists contain other lists. For instance, a directory can have other directories inside it, those child directories can contain additional directories, and so on.

Solve this problem with a recursive iterator, an iterator that works with multilevel lists. The following examples demonstrate directory iteration for subdirectories.

PHP 4: Recursively Reading Files in a Directory

In PHP 4, the easiest way to process all the files in a directory and its children is to call a function recursively:

function iterate_dir($path) {
    $files = array( );
    if (is_dir($path) & is_readable($path)) {
        $dir = dir($path);
        while (false !=  = ($file = $dir->read( ))) {
            // skip . and .. 
            if (('.' =  = $file) || ('..' =  = $file)) {
                continue;
            }
            if (is_dir("$path/$file")) {
                $files = array_merge($files, iterate_dir("$path/$file"));
            } else {
                array_push($files, $file);
            }
        }
        $dir->close( );
    } 
    return $files;
}

$files = iterate_dir('/www/www.example.com');
foreach ($files as $file) {
  print "$file\n";
}
email.html
               logo.gif
               php.gif
               auth.inc
               user.inc
               index.html
               search.html

This function loops through every file in the current directory. If the file is a directory, the function recursively calls itself and passes the subdirectory name as the argument. These results are then merged back into a master list of files stored in the $files array. When a file is not a directory, it’s added to the list ...

Get Upgrading to PHP 5 now with O’Reilly online learning.

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.