Reading directory list – new PHP5 way

It has been long time for using opendir, readdir functions or even scandir for reading directory listing from the disk.  Even myself still using it when in need.

Its time to update your snipped library with new PHP5 object oriented code. This is definitely not a new new thing, but still I want to make an article on it to attract more users to use this feature.

Retrieve directory listing

Using new Iterator thing

$directory = new DirectoryIterator("/tmp/mystuff");
foreach($directory as $entry) {
   // Do your stuff here
 
}

The good thing here is that $entry is an object and you can use some useful methods like

// Checks if entry is regular file, this way you skip '.' or '..' entries
$entry->isFile(); 
 
// Checks if entry is a directory
$entry->isDir()  
 
// Get FULL path including filename, for passing to processing function
$entry->getPathname()

As well as others like $entry->getOwner(), getPerms, getSize, isWritable

Retrieve recursive directory listing

Another magic feature it is easy to convert code above to do recursive directory listing, look

$directory = new RecursiveDirectoryIterator("/tmp/mystuff");
foreach(new RecursiveIteratorIterator($directory) as $entry) {
   // Do your stuff here
 
}

See more docs on RecursiveDirectoryIterator, it has second parameter to control what is included in final list.

 

Did you find this post useful? Support the the author ($10)
My Google Profile+

2 comments

  1. Hi,

    You might want to filter out the ‘.’ and ‘..’ dirs. Thanks to the isDot() class method it is super easy:

    if ($entry->isDir() && !$entry->isDot())

    King regards

Leave a Reply

Your email address will not be published.