Using DirectoryIterator to List Files in PHP

May 18th, 2006

During the days of PHP4, the most common way of showing the files in a directory was like so:

PHP:
  1. if ($handle = opendir('/home/fernando/temp')) {
  2.    while (false !== ($file = readdir($handle))) {
  3.        if ($file != "." && $file != "..") {
  4.            print "$file <br />";
  5.        }
  6.    }
  7.    closedir($handle);
  8. }

However, if your PHP version has now been upgraded to PHP 5, you can take advantage of DirectoryIterator instead. This class (don't get scared) is part of the SPL library that is now bundled within PHP 5.

DirectoryIterator

Using DirectoryIterator is very easy:

PHP:
  1. $dir = new DirectoryIterator( '/www/test/' );
  2. foreach($dir as $file )
  3. {
  4.   echo $file->getFilename();
  5. }

Along with getFilename(), there are several other functions that you can use to aid you with handling what files are used, and what information you can produce. The most commonly used ones are below:

  • getATime() - get last access time of file (as unix timestamp)
  • getCTime() - get last change time of file (as unix timestamp)
  • getMTime() - get last modification time of file (as unix timestamp)
  • getFilename() - get file name
  • getGroup() - get file's group
  • getOwner() - get file's owner
  • getPath() - get file's path excluding filename
  • getPathname() - get file's path including filename
  • getPerms() - get file's permissions
  • getSize() - get file size in bytes
  • getType() - get file type (not MIME Type)
  • isDir() - check if it is a directory
  • isDot() - check if it is either '.' or '..'
  • isExecutable() - check if file is executable
  • isFile() - check if it is a file
  • isLink() - check if it is a link
  • isReadable() - check if it is readable
  • isWritable() - check if it is writeable

Armed with this information, we can now bring up a useful list of files along with creation date, in a directory:

PHP:
  1. $dir = new DirectoryIterator( '/www/test/' );
  2. foreach($dir as $file )
  3. {
  4.   if(!$file->isDot() && !$file->isDir()) {
  5.     echo "FileName: ".$file->getFilename();
  6.     echo "Size: ".number_format(($file->getSize()/1024),2)." Kb";
  7.     echo "Date Created: ".date("D d M Y H:i:sa",$file->getCTime());
  8.   }
  9. }

which would give me a nice listing like so:

FileName: index.html
Size: 0.01 Kb
Date Created: Tue 07 Mar 2006 10:36:17am

FileName: image.jpg
Size: 31.48 Kb
Date Created: Thu 18 May 2006 17:59:04pm

Selecting Files

Now what if you only wanted to displag .jpg or .jpeg files? The simplest way is to perform a regular expression on the filename to check that it does indeed match that file extension:

PHP:
  1. $dir = new DirectoryIterator( '/www/test/' );
  2. foreach($dir as $file )
  3. {
  4.   if(!$file->isDot() && !$file->isDir() && preg_match("/.jpe?g$/",$file->getFilename())) {
  5.     echo "FileName: ".$file->getFilename();
  6.     echo "Size: ".number_format(($file->getSize()/1024),2)." Kb";
  7.     echo "Date Created: ".date("D d M Y H:i:sa",$file->getCTime());
  8.   }
  9. }

and would give me just this:

FileName: image.jpg
Size: 31.48 Kb
Date Created: Thu 18 May 2006 17:59:04pm

As you can see, this new library of functions is a lot easier to use, and understand. Next time, we'll discuss the use of RecursiveDirectoryIterator to recurse through a directory and its subdirectories. Enjoy!


 Add to del.icio.us    Digg this    Technorati

Related Posts:

Entry Filed under: PHP 5

10 Comments Add your own

  • 1. zaa  |  May 23rd, 2006 at 9:51 pm

    Actually !$file->isDot should be written as !$file->isDot()

  • 2. Khalid  |  May 24th, 2006 at 10:12 am

    Nice Spot - i've fixed it now.

  • 3. zaa  |  April 21st, 2007 at 5:21 pm

    Already !$file->isDot should be written as !$file->isDot()

  • 4. lo  |  May 5th, 2007 at 1:27 pm

    yo freebird is dumb? can i please have a raise!?
    do you like jelly donuts??????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????????/

  • 5. Dru  |  October 29th, 2007 at 11:06 pm

    Is there a sorting function using DirectoryIterator? That would help.

  • 6. Kwittman  |  November 11th, 2007 at 2:54 pm

    Thank you for posting this!

  • 7. chaoskaizer  |  December 10th, 2007 at 6:50 pm

    nice, IMO if you just looking for files it should be written as

    if ($file->isFile){
    // do something
    }

  • 8. jon  |  February 18th, 2008 at 11:08 pm

    What if I want the directories in a directory? Does DirectoryIterator only return the files?

  • 9. Luke  |  March 15th, 2008 at 9:21 pm

    When is that RecursiveDirectoryIterator article coming?

  • 10. Tims Blog » Blog Ar&hellip  |  March 28th, 2008 at 5:00 pm

    […] using directoryiterator to list files in php […]

Leave a Comment

Required

Required, hidden

Some HTML allowed:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <code> <em> <i> <strike> <strong>

Trackback this post  |  Subscribe to the comments via RSS Feed


Calendar

May 2006
M T W T F S S
« Apr   Jun »
1234567
891011121314
15161718192021
22232425262728
293031  

Most Recent Posts