UltraMega Blog
2Mar/090

Working With Directories in PHP

PHP offers some built in file system related functions that allow you to work directly with files and directories. This tutorial will focus on working with directories. It will explain how to open and list the contents of directories, which is actually pretty easy to do.

The process goes pretty much like this: open a directory, read the directory in a loop, check each entry to see if it is a file or directory, display each accordingly, then close the directory.

The first step is to open the directory using the opendir function which accepts a string representing the path and returns a handle if successful.

$dir = '/path/to/your/files/';
if($dh = opendir($dir)) {
}

If successful, we need to start reading the contents of the directory using the readdir function. This accepts the handle created earlier and returns the name of one file. We will run this in a loop until it returns false, and then we use closedir on the handle. We need to use the !== operator so it doesn't confuse a file named "0" as false. (more on comparison operators)

$dir = '/path/to/your/files/';
if($dh = opendir($dir)) {
   while(($file = readdir($dh)) !== false) {
   }
   closedir($dh);
}

We probably also want to filter out the "." and ".." entries, which are shortcuts for the current and parent directory respectively.

$dir = '/path/to/your/files/';
if($dh = opendir($dir)) {
   while(($file = readdir($dh)) !== false) {
      if($file != '.' && $file != '..') {
      }
   }
   closedir($dh);
}

To finish up, we should check each entry to see if it is a directory, so we differentiate between files and directories (here we add a "-" in front of directories. Here is the final code. It displays each item inside a div tag to make a basic list.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
$dir = '/path/to/your/files/';
if($dh = opendir($dir)) {
   while(($file = readdir($dh)) !== false) {
      if($file != '.' && $file != '..') {
         if(is_dir($dir . $file)) {
            echo "<div> - " . $file . "</div>\n";
         }
         else {
            echo "<div>" . $file . "</div>\n";
         }
      }
   }
   closedir($dh);
}

You should be able to use this as a base for anything that requires reading a directory. Thanks for reading.

Posted by Steve

Comments (0) Trackbacks (0)

No comments yet.


Leave a comment

This site uses Akismet to reduce spam. Learn how your comment data is processed.

No trackbacks yet.