350

What would be the best way to list all the files in one directory with PHP? Is there a $_SERVER function to do this? I would like to list all the files in the usernames/ directory and loop over that result with a link, so that I can just click the hyperlink of the filename to get there. Thanks!

Shadowpat
  • 3,577
  • 2
  • 14
  • 14

2 Answers2

769

You are looking for the command scandir.

$path    = '/tmp';
$files = scandir($path);

Following code will remove . and .. from the returned array from scandir:

$files = array_diff(scandir($path), array('.', '..'));
Mukesh Chapagain
  • 25,063
  • 15
  • 119
  • 120
miah
  • 10,093
  • 3
  • 21
  • 32
  • 100
    This is the more elegant solution. I would also add/recommend $files = array_diff(scandir($path), array('..', '.')); – kyle Jul 02 '14 at 21:31
  • 36
    Actually not `$files` but `$filesAndDirs` – vladkras Jun 28 '16 at 15:08
  • 1
    @GustvandeWal on my experience, most of `scandir()` on my code and reviews used something like `foreach(scandir($x) as $file) if ($file selection) {...}`, and `glob()` not need the `if`, neither regular expressions or array_diffs for selection. – Peter Krauss Sep 14 '16 at 01:38
  • 14
    $files = array_values(array_diff(scandir($path), array('.', '..'))); // this will reindex – SagarPPanchal Feb 14 '17 at 18:04
  • 4
    I experienced a small snag finding the directory. `$files = array_diff(scandir(__DIR__ .$path), array('.', '..'));` solved the problem. From http://stackoverflow.com/questions/11885717/scandir-fail-to-open-directory – Stack Underflow Apr 26 '17 at 16:33
  • 4
    Use **array_values()** to reindex the array after **array_diff()** `array_values(array_diff(scandir($path), array('..', '.')));` – vinsa Sep 18 '20 at 15:27
312

Check this out : readdir()

This bit of code should list all entries in a certain directory:

if ($handle = opendir('.')) {

    while (false !== ($entry = readdir($handle))) {

        if ($entry != "." && $entry != "..") {

            echo "$entry\n";
        }
    }

    closedir($handle);
}

Edit: miah's solution is much more elegant than mine, you should use his solution instead.

Orel Biton
  • 3,478
  • 2
  • 15
  • 15
  • 4
    this works perfect too `$files = scandir($imgspath); $total = count($files); $images = array(); for($x = 0; $x <= $total; $x++): if ($files[$x] != '.' && $files[$x] != '..') { $images[] = $files[$x]; } endfor;` – Patrick Mutwiri May 13 '15 at 06:15
  • 3
    Use `glob()` better! http://php.net/manual/en/function.glob.php – Peter Krauss Aug 26 '16 at 20:07
  • This might be a better solution when performance matter: [readdir-vs-scandir](https://stackoverflow.com/questions/8692764/readdir-vs-scandir). – SAMPro Jun 05 '18 at 09:32
  • 2
    your advantage is: you can filter in one single loop. Say you only want to have `.html` files and no files containing `404`, you can do this on one loop with your solution. Miah you have to loop over the results again – Toskan Oct 12 '19 at 22:50