Skip to Content
PHP Cookbook
book

PHP Cookbook

by David Sklar, Adam Trachtenberg
November 2002
Intermediate to advanced
640 pages
16h 33m
English
O'Reilly Media, Inc.
Content preview from PHP Cookbook

19.7. Processing All Files in a Directory Recursively

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.

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);

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 ...

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
PHP Cookbook, 2nd Edition

PHP Cookbook, 2nd Edition

Adam Trachtenberg, David Sklar
PHP Cookbook, 3rd Edition

PHP Cookbook, 3rd Edition

David Sklar, Adam Trachtenberg
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe

Publisher Resources

ISBN: 1565926811Supplemental ContentCatalog PageErrata