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