PHP: Display a customizeable list of files in a directory

Apache gives you a list of files in an empty directory by default, but sometimes you will want to show a list of files that are in a directory through PHP so that you can customize the output of the list, and make a “pretty” listing of files. Here’s the basic code to make a list.


 if ($handle = opendir('.')) {
   while (false !== ($file = readdir($handle)))
          if ($file != "." && $file != "..")
          	$thelist .= '<a href="'.$file.'">'.$file.'</a>';
<P>List of files:</p>


That’s about all you need to do. You could also put the list of files into an array if you felt like it, or use this as the beginning for a thumbnail page, which is what I used it for.

Lowell Heddings is the founder and Editor-in-Chief of How-To Geek. He spends all his free time making sure this site can bring you fresh geekery on a daily basis, and has been doing so for over eleven years.