Working with Directories

Now that you have mastered working with individual files, it is time to take a look at the larger file system—specifically, how PHP handles directories . 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(). The first of the three 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.

The readdir() function 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 it is stored by the file system. Once it reaches the end of the directory, it will return false. Here is a complete example of how to list the contents of a directory:

    $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—!= = 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. In that example, closedir() takes our directory handle as its ...

Get PHP in a Nutshell now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.