21

Possible Duplicates:
Get the Files inside a directory
PHP: scandir() is too slow

I have a directory with tens of thousands of files in it and I want to display a list of these files on a page. I tried doing it with scandir and it takes forever. What would be an efficient method of achieving this?

Community
  • 1
  • 1
John
  • 211
  • 1
  • 2
  • 3
  • 1
    Which of these have you tried: http://stackoverflow.com/search?q=list+files+directory+php – Gordon Mar 30 '11 at 07:27
  • 1
    You will also want to read [Putting Glob to Test](http://www.phparch.com/2010/04/28/putting-glob-to-the-test/) – Gordon Mar 30 '11 at 07:28
  • i've tried those methods - they work fine with a thousand or so files but it takes an age to return hundreds of thousands of files into an array – John Mar 30 '11 at 07:33
  • 2
    Possible duplicate of http://stackoverflow.com/questions/5172784/php-scandir-is-too-slow – Maxime Pacary Mar 30 '11 at 07:33
  • @John if you really already tried scandir, opendir, glob and iterators then please update your question to state that. maybe even add some code and performance numbers. there is no point in having us repeat all the methods that can easily be found in the dozens other questions asking the same. – Gordon Mar 30 '11 at 07:36
  • It isn't a good idea to have hundreds of thousands of files in a directory on any operating platform that I know... common practise is always to split them across subdirectories – Mark Baker Mar 30 '11 at 08:00

3 Answers3

9

I recommend using DirectoryIterator or RecursiveDirectoryIterator.

eisberg
  • 3,731
  • 2
  • 27
  • 38
  • 8
    I recommend `FilesystemIterator` over `DirectoryIterator`. – salathe Mar 30 '11 at 08:53
  • @salathe +1 See also question [Difference between `DirectoryIterator` and `FileSystemIterator`](http://stackoverflow.com/questions/12532064/difference-between-directoryiterator-and-filesystemiterator). Cheers ;-) – oHo Sep 28 '14 at 20:53
1

I haven't benchmarked them, but your other options are

glob() - http://php.net/manual/en/function.glob.php

opendir() - http://www.php.net/manual/en/function.opendir.php

JohnP
  • 49,507
  • 13
  • 108
  • 140
1
$directory=opendir($_SERVER['DOCUMENT_ROOT'].'/directory/');
  while ($file = readdir($directory)) {
    if($file!="." && $file!=".."){
      echo $file."<br>";
    }
  }
closedir($directory);
HispaJavi
  • 21
  • 1