Directory routines demo

Functions demonstrated
opendir("/path/dir")
closedir()
readdir()
rewinddir()

It is often important to be able to "walk" through a directory and do something based on the files in the directory. PHP includes functions that will let you do just that. The first thing to do is to open the directory. The syntax for doing that is:

<?$dir = opendir("/path/dir")?>

Once opened, the readdir($dir) function may be used to read entries in the directory sequentially. The first call to readdir($dir) will return the first entry and the second call the second entry, etc.

The rewinddir($dir) function can be used to move the directory pointer back to the beginning resulting in the next call to readdir($dir) returning the first entry in the directory.

And, at the end, the closedir($dir) function should be called.

Below is a simple example which reads the contents of the directory in which this PHP script resides.

Code:

<?
$dir = opendir(".");
  while($file = readdir($dir)) {
    echo "$file<BR>";
  }
  closedir($dir);
?>

Output:

.
dir.php
..

In PHP3, there is also an object-oriented syntax for working with directories. So, for example, the code above would be:

<?
$dir = dir(".");
  while($file = $dir->read()) {
    echo "$file<BR>";
  }
  $dir->close();
?>

Output:

.
dir.php
..