HomePHP Page 8 - File And Directory Manipulation In PHP (part 2)
Diving Into Directories - PHP
Now that you know the basics of reading and writing files, this second segment of our tutorial on the PHP filesystem API takes you into deeper waters, showing you how to copy, delete and rename files; scan directories; work with uploaded files over HTTP; perform pattern matches on file names; and read and write to processes instead of files.
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.