Home  >  Article  >  Backend Development  >  php递归获取目录内文件(包含子目录)封装类分享_php实例

php递归获取目录内文件(包含子目录)封装类分享_php实例

WBOY
WBOYOriginal
2016-05-17 08:51:561014browse

代码如下:

复制代码 代码如下:

function readFileFromDir($dir) {
    if (!is_dir($dir)) {
        return false;
    }
    //打开目录
    $handle = opendir($dir);
    while (($file = readdir($handle)) !== false) {
        //排除掉当前目录和上一个目录
        if ($file == "." || $file == "..") {
            continue;
        }
        $file = $dir . DIRECTORY_SEPARATOR . $file;
        //如果是文件就打印出来,否则递归调用
        if (is_file($file)) {
            print $file . '
';
        } elseif (is_dir($file)) {
            readFileFromDir($file);
        }
    }
}

调用方式:

复制代码 代码如下:

$dir = '/home/www/test';
readFileFromDir($dir);

查看php手册的话,还有一个方法scandir也可以使用,不过这个方法会一次性获取单级目录下的所有文件,存放到数组里,如果目录里的文件比较多的话,会卡。

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn