How to traverse directories and files in PHP?

To traverse directories and files, you can utilize PHP’s scandir() function and recursive method.

Firstly, use the scandir() function to retrieve the names of all files and subdirectories in a directory. Then, iterate through the returned array using a loop and check if each element is a file or a directory.

If it is a directory, use recursive function call to traverse the directory and perform the same operation. If it is a file, handle it accordingly.

Here is an example code:

function traverseDirectory($dir) {
    $files = scandir($dir); // 获取目录中的所有文件和子目录的名称

    foreach ($files as $file) {
        if ($file != '.' && $file != '..') { // 排除当前目录和上级目录
            $path = $dir . '/' . $file; // 文件或子目录的路径

            if (is_dir($path)) { // 如果是目录,则递归遍历子目录
                traverseDirectory($path);
            } else { // 如果是文件,则进行相应的处理
                echo $path . PHP_EOL;
                // 在此处可以对文件进行操作,如读取内容、复制、删除等
            }
        }
    }
}

// 调用遍历函数
$directory = 'path/to/directory'; // 要遍历的目录路径
traverseDirectory($directory);

In the example above, the traverseDirectory() function takes a directory path as a parameter and uses the scandir() function to get the names of all files and subdirectories in that directory. Then, it loops through the returned array, and performs appropriate actions based on whether the element is a file or a directory. If it is a directory, it recursively calls itself; if it is a file, it performs the necessary operation.

Please modify the directory path and file processing code according to actual needs.

bannerAds