Home  >  Article  >  Backend Development  >  PHP recursively obtains files in a directory, including subdirectories

PHP recursively obtains files in a directory, including subdirectories

巴扎黑
巴扎黑Original
2016-11-12 10:15:011256browse

Encapsulated into a method, the code is as follows:

Php code

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); } } }

Calling method:

Php code

$dir = '/home/www/test';

readFileFromDir($dir);

If you look at the PHP manual, there is another method scandir that can also be used, but this method will get all the files in a single-level directory at once and store them in an array. If there are many files in the directory, it will get stuck.


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