Using PHP to read files from a directory
Monday 31st August 2009
One of the first things that I learnt how to do in PHP years ago was to read files from a directory. I used it for a couple of projects and then promptly forgot about it, until recently it solved a problem that I encountered. It’s a really simple, and actually powerful, tool which can help create a list of files, or even a dynamically generated music playlist or photo gallery.
Starting off, there are 2 variables that you need to specify:
$fileDir– this is the location of your directory on your server (ie, the path)$urlloc– the address of the folder as accessed in a web browser
We’ll use the $fileDir variable to locate the folder and read the files within, and the $urlloc variable is used to display the files (if images) or link to the files. The premise here is to open the directory $fileDir, loop through it, and for each file in the folder output a link to that file. This can be organised in a list if required with a little bit of extra code.
//specify our two variables for accessing the directory.
//replace "folder" with your folder name
$fileDir = $_SERVER['DOCUMENT_ROOT'] . '/folder/';
$urlloc = "http://".$_SERVER['HTTP_HOST'] . '/folder/';
//we're creating a list of files, so we start it
$result = "<ul>";
//opendir function opens the folder for reading
$handle = opendir($fileDir);
//while loop, which continues to execute until the
//readdir function finishes traversing the directory
while (($file = readdir($handle)) !== FALSE) {
//this allows the list to include
//links to subdirectories
if (is_dir($fileDir . $file)) continue;
//for each file, place a link to the
//file in the list
//by appending it onto $result
$thisfile = $file;
$result.= "<li><a href=\"".$urlloc.$thisfile."\"
rel=\"external\">".$thisfile."</li>";
}
//close off the list
$result.= "</ul>";
//print the output to the screen
echo $result;
You can filter the results of the search to particular file types, or files with name matches, using one more line of cold with a regular expression
//while loop, which continues to execute until the
//readdir function finishes traversing the directory
while (($file = readdir($handle)) !== FALSE) {
//this allows the list to include
//links to subdirectories
if (is_dir($fileDir . $file)) continue;
//selecting only jpg images
if (!eregi('^.*\.jpg$', $file)) continue;
//for each file, place a link to the
//file in the list
//by appending it onto $result
$thisfile = $file;
$result.= "<li><a href=\"".$urlloc.$thisfile."\"
rel=\"external\">".$thisfile."</li>";
}
I’ve put together a live example, which shows a list output and a small image gallery created using this quick and handy loop.

Kevin McMahon is a web developer from Ireland, currently living and working in Dublin. 
