8.13 Working with directories: opendir(), readdir(), and closedir()This is NOT the latest copy of this book; click here for the latest version.
resource opendir ( string path)
string readdir ( resource dir_handle)
void closedir ( resource dir_handle)
Now you have mastered working with individual files, it is time to take a look at the larger file system - specifically how PHP handles directories. As you have seen so far, working with files is actually quite easy, and you will be glad to hear that working with directories is little different
Let's start with something simple - listing the contents of a directory. There are three functions we need to perform this task - opendir(), readdir(), and closedir(). opendir() takes one parameter, which is the directory you wish to access. If it opens the directory successfully, it returns a handle to the directory, which you should store away somewhere for later use.
Readdir() takes one parameter, which is the handle that opendir() returned. Each time you call readdir() on a directory handle, it returns the filename of the next file in the directory in the order in which they are stored by the file system. Once it reaches the end of the directory, it will return false. So, here is a complete example on how to list the contents of a directory:
<?php
$handle = opendir('/path/to/directory')
if ($handle) {
while (false !== ($file = readdir($handle))) {
print "$file<BR />\n";
}
closedir($handle);
} ?>
At first glance, the 'while' statement might look complicated, but it is really quite easy - !== is the PHP operator for "not equal and not the same type as". The reason we do it this way as opposed to just while ($file = readdir($handle)) is because it is sometimes possible for the name of a directory entry to evaluate to false which would end our loop prematurely.
As you can see, closedir() takes our directory handle as its sole parameter, and it just cleans up after opendir().
Save the code into a file, 'dirlist.php', and give it a try. You will notice that it lists the . and .. directory entries - I will leave it as an exercise to the reader to filter out these entries! To get you thinking, here is a small hint for you: the "continue" keyword tells PHP "Skip the rest of this loop iteration and continue on from the start of the next iteration".
|
Want to see this stuff in print? PHP in a Nutshell takes the core topics covered here, adds in thousands of edits from the editorial team and myself, and combines them to make an unbeatable reference for PHP programmers at all levels.
My latest book has hundreds more tips on how to use PHP, Apache, and MySQL, plus Perl, Python, shell scripts, performance tuning, and more!
|