Discover & Rate New Music Check out ChartVote. Promote the music you like.


List all files in a directory with PHP

This code snippet displays a hyper linked list of all the files contained in a specified folder. I find myself always coming back to this very useful piece of code. I can't count how many times I've used this.

PHP:
  1. <?
  2.     // Define the full path to the folder whose contents you want to list
  3.     $path = "/home/user/public/foldername/";
  4.     // Open the directory
  5.     $dir_handle = @opendir($path) or die("Error opening $path");
  6.     // Loop through the files
  7.     while ($file = readdir($dir_handle)) {
  8.       if($file == "." || $file == ".." || $file == "index.php" ) { continue; }
  9.    
  10.       echo "<a href=\"$file\">$file</a><br />";
  11.     }
  12.     // Close
  13.     closedir($dir_handle);
  14. ?>


One Comment

  1. Evan on May 31st, 2008

    I love the script, and have found sooo many uses. I have had to make one minor change, however, due to a linking problem. You have forgotten to add the variable $path in front of the variable $file... The link won't work unless you make this one minor change.

    Other than that, GREAT JOB!

Leave a Reply

RSS Feed



Recommended Sites