How to work with directories using php

Post Reply
User avatar
Neo
Site Admin
Site Admin
Posts: 2642
Joined: Wed Jul 15, 2009 2:07 am
Location: Colombo

How to work with directories using php

Post by Neo » Mon Mar 01, 2010 12:34 am

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.

Code: Select all

$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)

Code: Select all

$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.

Code: Select all

$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.

Code: Select all

$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.
Post Reply

Return to “PHP & MySQL”