简体   繁体   中英

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:

  • 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?

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

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('.');

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM