How to traverse directories and subdirectories in PHP?

In PHP, you can use the scandir() function to traverse directories and subdirectories. Below is an example code:

function traverseDirectory($dir) {
    // 扫描目录并获取文件和子目录列表
    $files = scandir($dir);
    
    // 遍历列表中的每个文件和目录
    foreach($files as $file) {
        // 跳过当前目录和上级目录
        if ($file == '.' || $file == '..') {
            continue;
        }
        
        // 拼接文件或目录的完整路径
        $path = $dir . '/' . $file;
        
        // 如果是目录,则递归调用traverseDirectory函数
        if (is_dir($path)) {
            traverseDirectory($path);
        } else {
            // 打印文件路径
            echo $path . "\n";
        }
    }
}

// 调用函数遍历目录
traverseDirectory('/path/to/directory');

The above code will traverse all files in the specified directory and its subdirectories, printing out the complete file path. You can replace /path/to/directory with the actual directory path.

bannerAds