PHP Directory Traversal with scandir

In PHP, you can use the scandir function to browse through all the files and subdirectories in a specified directory. Here is a simple example code:

$dir = "/path/to/directory";

// 扫描目录并获取目录中的文件和子目录
$files = scandir($dir);

// 遍历文件和子目录
foreach ($files as $file) {
    // 排除当前目录(.)和上级目录(..)
    if ($file != '.' && $file != '..') {
        // 判断是否为目录
        if (is_dir($dir . '/' . $file)) {
            echo "Directory: " . $file . "<br>";
            
            // 遍历子目录
            $subfiles = scandir($dir . '/' . $file);
            foreach ($subfiles as $subfile) {
                if ($subfile != '.' && $subfile != '..') {
                    echo "File: " . $subfile . "<br>";
                }
            }
        } else {
            echo "File: " . $file . "<br>";
        }
    }
}

In the given code, firstly specify the directory path to iterate through, then use the scandir function to retrieve all files and subdirectories in the directory, and finally loop through to output the names of the files and subdirectories. It is important to note that while iterating, the current directory “.” and the parent directory “..” are excluded.

bannerAds