Affordable Web Hosting with Excellent Customer Support internet connection free month hosting

PHP Read Directory

Opening and reading directory contents with PHP.

Obtain a listing of all files in a directory:

Let's use a directory called my_files which is publicly accessible via HTTP protocol. For this we will need the directory to exist, and we need to give our php interpreter the full server path to the directory which we are reading.

To obtain the full path we do this:

$PATH = $_ENV['DOCUMENT_ROOT'];

This will get your path in the server to your publicly accessible directory (example: /var/www/jpes/webshare/)

Next we define our directory in the account, open the directory, and use a while loop to print all files within.

$d=$PATH.'/my_files/'; #define which dir you want to read

$dir = opendir($d); #open directory
while ($f = readdir($dir)) { #read one file name
 echo "file:$f<br>\n"; #print name of each file found
}

This will print all the files in the directory. Including . and .. (What is this?) Unix systems use dot to reference to the present directory and two dots for the parent directory.

Let's do something more useful. Imagine you only want to list text files in your directory. Also, let's store the files in an array for later use. The code would be:

$PATH = $_ENV['DOCUMENT_ROOT'];

$d=$PATH.'/my_files/';

$files=array(); #initialize array

$dir = opendir($d);
while ($f = readdir($dir)) {

 if (eregi("\.txt",$f)){ #if filename matches .txt in the name
    array_push($files,"$f"); #push into $files array
 }
}

One final example. What if you want to read into your array everything but .jpg, . and .. files ?

$PATH = $_ENV['DOCUMENT_ROOT'];

$d=$PATH.'/my_files/';

$files=array();

$dir = opendir($d);
while ($f = readdir($dir)) {

 if (!eregi("\.jpg",$f) && $f!=='.' && $f!=='..'){ #if does not match .jpg . and ..
    array_push($files,"$f");
 }
}