phprecursionscandir

PHP: List all files in a folder recursively and fast


I am looking for the fastest way to scan a directory recursively for all existing files and folders.

Example:

 - images
 -- image1.png
 -- image2.png
 -- thumbnails
 --- thumb1.png
 --- thumb2.png
 - documents
 -- test.pdf

Should return:

So I would start with:

$filesandfolders = @scandir( $path );
foreach ($filesandfolders as $f){
 if(is_dir($f)){
  //this is a folder
 } else {
 //this is a file 
}
}

But it this the fastest way?


Solution

  • You could use the RecursiveDirectoryIterator - but I doubt, it's faster than a simple recusive function.

    $iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator('/path/to/folder'));
    foreach ($iterator as $file) {
        if ($file->isDir()) continue;
        $path = $file->getPathname();
    }