Listing files with PHP

2010-04-29

I’ve just finished writing the code for the archive on the site and I thought I’d share it with you. The code will list all files in a chosen folder. The code also shows how to filter out certain files, and how it is possible to sort the list alphabetically.

<?php
//Path to the folder where you want to list the files.
$dir = "/path/to/folder"; 
//Attempt to create a handle for the folder. 
if($handle = opendir($dir)) { 
  //Defines an array that will store files in the folder.
  $files = array(); 

  //Iterate through all files in the folder.
  while($file = readdir($handle)) { 

    //Removes the folders "." and ".." from the list. 
    if($file != "." && $file != "..") { 

      //Verifies that it is not a folder.
      if(!is_dir("$dir/$file")) { 
        //Add the file to the array.
        $files array_push($files, $file); 
      } 
    } 
  } 

  //Sort the files alphabetically.
  sort($files); 

  //Prints all files in the array with a link.
  foreach($files as $file) { 
    echo("<a href="$dir/$file">$file</a><br />"); 
  } 
} 
//Prints a text if the folder could not be opened.
else { 
  echo("Could not open folder."); 
} 
?>