使用 PHP 获取目录的层次结构

2022-01-01 00:00:00 directory file filesystems php

我正在尝试查找指定目录下的所有文件和文件夹

I'm trying to find all the files and folders under a specified directory

例如我有/home/user/stuff

For example I have /home/user/stuff

我想回来

/home/user/stuff/folder1/image1.jpg
/home/user/stuff/folder1/image2.jpg
/home/user/stuff/folder2/subfolder1/image1.jpg
/home/user/stuff/image1.jpg

希望这是有道理的!

推荐答案

function dir_contents_recursive($dir) {
    // open handler for the directory
    $iter = new DirectoryIterator($dir);

    foreach( $iter as $item ) {
        // make sure you don't try to access the current dir or the parent
        if ($item != '.' && $item != '..') {
            if( $item->isDir() ) {
                // call the function on the folder
                dir_contents_recursive("$dir/$item");
            } else {
                // print files
                echo $dir . "/" .$item->getFilename() . "<br>";
            }
        }
    }
}

相关文章