php递归读取目录及子目录下所有文件

<?php
function searchDir($path,&$data){
        if(is_dir($path)){
                $dp=dir($path);
                //如果子目录可读,则递归读取该目录
                while($file=$dp->read()){
                        if($file!='.'&& $file!='..'){
                                searchDir($path.'/'.$file,$data);
                        }
                }

        $dp->close();
        }
        if(is_file($path)){
                $data[]=$path;
        }
}

function getDir($dir="."){
        $data=array();
        searchDir($dir,$data);
        return   $data;
}
fwrite(STDOUT,"Please input dir name:");
$dir = trim(fgets(STDIN));
print_r(getDir($dir));

        用法:将以上代码保存为dir.php,在命令模式下执行该文件。

# php dir.php
# Please input dir name: .
Array
(
    [0] => ./cms0517.zip
    [1] => ./.bash_logout
    [2] => ./cms519.zip
    [3] => ./.Xauthority
    [4] => ./.cache/motd.legal-displayed
    [5] => ./.bash_history
    [6] => ./.ssh/authorized_keys
    [7] => ./dir.php
    [8] => ./.sudo_as_admin_successful
    [9] => ./.bashrc
    [10] => ./.profile
)

        结果以一维数组的方式遍历出dir.php文件夹下和其子文件夹下的文件。

发表评论?

0 条评论。

发表评论


注意 - 你可以用以下 HTML tags and attributes:
<a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <s> <strike> <strong>

This site uses Akismet to reduce spam. Learn how your comment data is processed.