Method in PHP for reading all file names in a directory and its subdirectories

There are several ways to read all filenames in a directory and its subdirectories. Here are two common methods:

  1. Traverse directories and subdirectories using a recursive function.
function getFiles($dir) {
    $files = [];
    $handle = opendir($dir);
    
    while (false !== ($file = readdir($handle))) {
        if ($file != "." && $file != "..") {
            $path = $dir.'/'.$file;
            
            if (is_dir($path)) {
                $files = array_merge($files, getFiles($path));
            } else {
                $files[] = $path;
            }
        }
    }
    
    closedir($handle);
    
    return $files;
}

$directory = "path/to/directory";
$files = getFiles($directory);

foreach ($files as $file) {
    echo $file."\n";
}
  1. Utilize the RecursiveDirectoryIterator class and RecursiveIteratorIterator class:
$directory = "path/to/directory";
$iterator = new RecursiveIteratorIterator(new RecursiveDirectoryIterator($directory));

foreach ($iterator as $file) {
    if ($file->isDir()) {
        continue;
    }
    
    echo $file->getPathname()."\n";
}

Both methods can be used to iterate through all the file names in a directory and its subdirectories. Choose the appropriate method based on the specific situation.

bannerAds