May 16, 2006

PHP Listing files in a directory

You will find other articles relevant to this document in these sections:
Cameron Manderson @ 5:23 pm

There are numerous variations to loop through a list of files in a directory in PHP. Here are a couple of simple ways:

Variation 1:

$folder = dir("/path/to/folder");
while($folderEntry = $folder->read()) {
    // $folderEntry is the resource. You can now check against it.
}

Variation 2:

if ($handle = opendir("/path/to/folder")) {
    while (false !== ($file = readdir($handle))) {
        // $file is the resource
    }
}

Both use assignment in a while loop to not only get the resource but terminate looping through your results. Variation 2 includes a condition to see if there were issues while openning the directory. You should consider how you will deal with these in your code.

Share and Enjoy:These icons link to social bookmarking sites where readers can share and discover new web pages.
  • del.icio.us
  • digg
  • Furl
  • Reddit
  • YahooMyWeb

No Comments »

No comments yet.

RSS feed for comments on this post. TrackBack URI

Leave a comment