PHP reading files in a directory, iterator

PHP reading files in a directory

Reading files in a directory with PHP used to be done procedurally as follows.

/* open the directory that the current file resides in and display file names */ $handle = opendir(dirname(__FILE__)); if ($handle) { while (false !== ($file = readdir($handle))) { if ($file != "." && $file != "..") { echo $file . "\n"; } } closedir($handle); }

The code above works ok and generally gives us enough information. But with PHP 5 Object Oriented Capabilities, we can use a much better approach.

/* open the directory that the current file resides in and display file names */ $directory = new DirectoryIterator(dirname(__FILE__)); foreach ($directory as $file) { if (!$file->isDot()) { echo $file->getFilename() . "\n"; } }

As our directory uses an iterator approach, we can loop through our values with the foreach statement making it a lot cleaner. We also have a lot of methods we can use to get more information about the files we find.

$directory = new DirectoryIterator(dirname(__FILE__)); $class_methods = get_class_methods($directory); foreach ($class_methods as $method_name) { echo $method_name . "\n"; } __construct getFilename getBasename isDot rewind valid key current next __toString getPath getPathname getPerms getInode getSize getOwner getGroup getATime getMTime getCTime getType isWritable isReadable isExecutable isFile isDir isLink getLinkTarget getRealPath getFileInfo getPathInfo openFile setFileClass setInfoClass

With all those methods available, we should have no problem at all traversing and interrogating our directory structure's with PHP.