Directory Iteration With DirectoryIterator() In PHP 5

The normal way of looping through a directory is to get a handle on the directory, then go through each item, making sure that the file is readable and is not "." or ".." before doing something with the file. Because this is done a lot the DirectoryIterator() object was created in PHP5 to simplify this process.

The constructor of the DirectoryIterator() object takes a single parameter, this is the path of the directory that is to be iterated over.

$dir = new DirectoryIterator('/');

To get the current working directory you can use the PHP function getcwd(). This will return the directory that the PHP script is being run from.

$dir = new DirectoryIterator(getcwd());

The previous bit of code will open up the root directory of your server. If you are on a Linux server you will see directories like dev, var, srv, etc, lib, home, root, sbin and usr.

With the object now created there are some different functions that can be used to look at different things. Here is a small list of what can be used:

  • isDot(): This function is used to see if the file is a "." or a "..".
  • isReadable (): Checks if the file is readable. If it is then it returns true, otherwise it is false.
  • next(): Moves the iterator onto the next item in the list.
  • valid(): This function checks to see if there is anything in the directory that can be iterated over. Basically, this function returns false if the iterator is at the end of the directory.
  • current(): Returns the name of the current file.

These functions can be put together in the following way. This snippet of code will print out all of the files in a directory.

while($dir->valid()){
 if(!$dir->isDot()){
  print $dir->current()."<br />";
 }
 $dir->next();
}

 

Add new comment

The content of this field is kept private and will not be shown publicly.
CAPTCHA
2 + 2 =
Solve this simple math problem and enter the result. E.g. for 1+3, enter 4.
This question is for testing whether or not you are a human visitor and to prevent automated spam submissions.