PHP: List all files in a folder recursively and fast

7k Views Asked by At

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:

  • images/image1.png
  • images/image2.png
  • images/thumbnails/thumb1.png
  • images/thumbnails/thumb2.png
  • documents/test.pdf

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?

2

There are 2 best solutions below

2
On BEST ANSWER

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();
}
0
On

I like this fancy output, any thoughts ?

function getAllContentOfLocation($loc)
{
    $scandir = scandir($loc);

    $scandir = array_filter($scandir, function ($element) {
        return !preg_match('/^\./', $element);
    });


    if (empty($scandir)) {
        echo '<p style="color:red">        Empty Dir</p>';
    }

    foreach ($scandir as $file) {
        $baseLink = $loc.DIRECTORY_SEPARATOR.$file;

        echo '<ol>';
        if (is_dir($baseLink)) {
            echo '<p style="font-weight:bold;color:blue">'.$file.'</p>';
            getAllContentOfLocation($baseLink);
        } else {
            echo $file.'';
        }
        echo '</ol>';
    }
}
//Call function and set location that you want to scan
getAllContentOfLocation('.');