Working with directories

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

If you're just starting out learning PHP, we recommend you skip these functions and focus on the scandir() function - it's much easier to use!

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

 

Next chapter: Deleting directories >>

Previous chapter: Changing file ownership

Jump to:

 

Home: Table of Contents

Follow us on Identi.ca or Twitter

Username:   Password:
Create Account | About TuxRadar