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 Lowell Heddings
Lowell is the founder and CEO of How-To Geek. He’s been running the show since creating the site back in 2006. Over the last decade, Lowell has personally written more than 1000 articles which have been viewed by over 250 million people. Prior to starting How-To Geek, Lowell spent 15 years working in IT doing consulting, cybersecurity, database management, and programming work.
Read Full Bio »