Skip to Main Content
PHP in a Nutshell
book

PHP in a Nutshell

by Paul Hudson
October 2005
Intermediate to advanced content levelIntermediate to advanced
372 pages
11h 35m
English
O'Reilly Media, Inc.
Content preview from PHP in a Nutshell

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

Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Start your free trial

You might also like

PHP Cookbook

PHP Cookbook

Eric A. Mann
Programming PHP

Programming PHP

Rasmus Lerdorf, Kevin Tatroe
Learning PHP

Learning PHP

David Sklar

Publisher Resources

ISBN: 0596100671Errata Page