Book HomePHP CookbookSearch this book

19.8. Processing All Files in a Directory

19.8.1. Problem

You want to iterate over all files in a directory. For example, you want to create a select box in a form that lists all the files in a directory.

19.8.2. Solution

Get a directory handle with opendir( ) and then retrieve each filename with readdir( ):

$d = opendir('/tmp') or die($php_errormsg);
while (false !== ($f = readdir($d))) {
    print "$f\n";
}
closedir($d);

19.8.3. Discussion

The code in the solution tests the return value of readdir( ) with the nonidentity operator (!==) so that the code works properly with filenames that evaluate to false, such as a file named 0.

The function readdir( ) returns each entry in a directory, whether it is a file, directory, or something else (such as a link or a socket). This includes the metaentries "." (current directory) and ".." (parent directory). To just return files, use the is_file( ) function as well:

print '<select name="files">';
$d = opendir('/usr/local/upload') or die($php_errormsg);
while (false !== ($f = readdir($d))) {
    if (is_file("/usr/local/upload/$f")) {
        print '<option> ' . $f . '</option>';
    }
}
closedir($d);
print '</select>';

Because readdir( ) returns only the filename of each directory entry, not a full pathname, you have to prepend the directory name to $f before you pass it to is_file( ).

PHP also has an object-oriented interface to directory information. The dir( ) function returns an object on which you can call read( ), rewind( ), and close( ) methods, which act like the readdir( ), rewinddir( ), and closedir( ) functions. There's also a $path property that contains the full path of the opened directory.

Here's how to iterate through files with the object-oriented interface:

print '<select name="files">';
$d = dir('/usr/local/upload') or die($php_errormsg);
while (false !== ($f = $d->read())) {
    if (is_file($d->path.'/'.$f)) {
        print '<option> ' . $f . '</option>';
    }
}
$d->close();

In this example, $d->path is /usr/local/upload.

19.8.4. See Also

Documentation on opendir( ) at http://www.php.net/opendir, readdir( ) at http://www.php.net/readdir, and the directory class at http://www.php.net/class.dir.



Library Navigation Links

Copyright © 2003 O'Reilly & Associates. All rights reserved.