List All Files in Directory with PHP

Posted by: Alex on January 26, 2014

I’ve created this simple bit of PHP to specify a directory, and then list the files grouped by folder on screen.

You can set certain files to be created as links, for easy browsing, they are: jpg,png,gif,docx,pdf,mp3. You can add any other file you want in the $files line.

I personally find this snippet very useful for document libraries and file management. As it saves you adding a file, and then having to manually list it in any index.php file. It will just automatically appear!

This example shows how it will turn a list of folders/documents etc into a clickable directory online:
PHP Dynamic Library Code Example

Just change the $path variable to point to your desired directory.

<? ob_start();

$path="example/Docs";

$directories = glob($path.'/*', GLOB_BRACE);
foreach($directories as $directory) {
 echo '
  <div class="container_16">
    <div class="grid_16"><table border="1" bordercolor="#FFFFFF" class="tables">
      <tr>
        <td colspan="2" bordercolor="#999999" bgcolor="#f4f4f4"><span class="table-title"><em><strong>';?><?=$directory; echo'</strong></em></span>
        </td>
      </tr>
      <tr>
        <td colspan="2" bordercolor="#CCCCCC"><table border="1" bordercolor="#FFFFFF">
          <tr bordercolor="#FFFFFF" class="forms">';
           $files = glob($directory. '/*.{jpg,png,gif,docx,pdf,mp3}', GLOB_BRACE);
           foreach($files as $file1) {
             $info1 = pathinfo($file1);
             $name = $info1['filename']; //index
             echo "<a href="$file1">$name</a><br>";
           }
           echo '
        </table></td>
      </tr>
    </table>
    </div><!—End Grid16—>
  </div><!—End Container16—>';
}
ob_flush(); ?>