温馨提示×

php readdir 可以递归吗

PHP
小樊
81
2024-11-27 13:42:48
栏目: 编程语言

PHP的readdir()函数本身不支持递归读取目录

function readDirectoryRecursively($directory) {
    $files = [];
    if (($handle = opendir($directory)) !== false) {
        while (($entry = readdir($handle)) !== false) {
            if ($entry == "." || $entry == "..") {
                continue;
            }
            $full_path = $directory . DIRECTORY_SEPARATOR . $entry;
            if (is_dir($full_path)) {
                $files = array_merge($files, readDirectoryRecursively($full_path));
            } else {
                $files[] = $full_path;
            }
        }
        closedir($handle);
    }
    return $files;
}

$directory = "path/to/your/directory";
$recursive_files = readDirectoryRecursively($directory);
print_r($recursive_files);

这个函数会递归地读取指定目录下的所有文件和子目录,并将它们的完整路径存储在一个数组中。你可以通过print_r()函数输出这个数组来查看结果。

0