Home > PHP > List files in a directory using php

List files in a directory using php

To display a list of files within a directory using PHP you need to use opendir() and readdir(). Below is a function that will return the list of files and remove the . and .. from the listing.

 
//full path of directory
$dir = "/var/www/images/";
 
function listFiles($dir){
 
//open directory and read its contents
if ($handle = opendir($dir)) {
while (false !== ($file = readdir($handle))) {
 
//only display filenames
if ($file != "." && $file != "..") {
echo "$file\n";
}
}
closedir($handle);
}
}
 

You might run into trouble trying to find the correct full path of the images. For example in a windows hosting environment the path could be  (c://blah/blah), in a Linux environment it could be (/var/www/blah/blah).

To find the exact path for your environment use phpinfo(). Once you have the php info look for the DOCUMENT_ROOT entry.

Post to Twitter Post to Plurk Plurk This Post Post to Yahoo Buzz Buzz This Post Post to Delicious Delicious Post to Digg Digg This Post Post to Ping.fm Ping This Post Post to Reddit Reddit Post to StumbleUpon Stumble This Post

  1. February 22nd, 2010 at 19:26 | #1

    Really good work about this website was done. Keep trying more – thanks!

  1. No trackbacks yet.
SEO Powered by Platinum SEO from Techblissonline