Spiga

List Files In A Directory Using PHP

by Gabi Solomon

Usually Apache will list all the files in a directory that doesnt have an index, unless the -indexes option is activated. Never the less sometimes in your programing you will need to list the files that are in a directory, not on the screen necessarily but at least save those files in a variable.

But enough small talk lets gets on with the actual code :

PHP:
  1. <?php
  2. $fileList=array();
  3. $dirPath='/path/to/your/dir/';
  4.  
  5.  if ($handle = opendir($dirPath)) {
  6.    while (false !== ($file = readdir($handle)))
  7.       {
  8.           if ($file != "." && $file != "..")
  9.       {
  10.             $fileList[] = $file;
  11.           }
  12.        }
  13.   closedir($handle);
  14.   }
  15. ?>
  16. <h3>List of files:</h3>
  17. <?php foreach ( $fileList as $f ) : ?>
  18. <P><?=$f?></p>
  19. <?php endforeach; ?>

Is that simple.

Cheers

Related Posts