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.

 

<?php
 if ($handle = opendir('.')) {
   while (false !== ($file = readdir($handle)))
      {
          if ($file != "." && $file != "..")
	  {
          	$thelist .= '<a href="'.$file.'">'.$file.'</a>';
          }
       }
  closedir($handle);
  }       
?>
<P>List of files:</p>
<P><?=$thelist?></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, better known online as the How-To Geek, spends all his free time bringing you fresh geekery on a daily basis. You can follow him on if you'd like.