Home > php教程 > php手册 > body text

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

WBOY
Release: 2016-06-06 20:26:04
Original
995 people have browsed it

php递归获取目录内文件封装类分享,可以递归子目录

代码如下:

复制代码 代码如下:


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也可以使用,不过这个方法会一次性获取单级目录下的所有文件,,存放到数组里,如果目录里的文件比较多的话,会卡。

Related labels:
source:php.cn
Statement of this Website
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
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!