File And Directory Manipulation In PHP (part 2) - Diving Into Directories (
Page 8 of 13 )
Thus far, most of the examples you've seen have dealt with individual files.
However, you often find yourself faced with the task of iterating over one or
more directories and processing the file list within each. In order to meet this
requirement, PHP offers a comprehensive set of directory manipulation functions,
which allow developers to read and parse an entire directory listing.
In order to demonstrate, consider the following simple example, which lists
all the files in the directory "/bin":
<?php
// initialize counter
$count = 0;
// set directory name
$dir = "/bin";
// open directory and parse file list
if (is_dir($dir))
{
if ($dh = opendir($dir))
{
// iterate over file list
// print filenames
while (($filename = readdir($dh)) !== false)
{
if (($filename != ".") && ($filename != ".."))
{
$count ++;
echo $dir . "/" . $filename . "\n";
}
}
// close directory
closedir($dh);
}
}
echo "-- $count FILES FOUND --";
?>
You can combine the script above with the getcwd() function discussed earlier
to obtain a list of all the files in the current working directory at any time -
I'll leave that to you to try out for yourself.