php recursively retrieves files in directories that of contains subdirectories to encapsulate class sharing

  • 2020-12-09 00:47:11
  • OfStack

The code is as follows:


function readFileFromDir($dir) {
    if (!is_dir($dir)) {
        return false;
    }
    // Open directory 
    $handle = opendir($dir);
    while (($file = readdir($handle)) !== false) {
        // Exclude the current directory and on 1 A directory 
        if ($file == "." || $file == "..") {
            continue;
        }
        $file = $dir . DIRECTORY_SEPARATOR . $file;
        // If it's a file, print it out; otherwise, call it recursively 
        if (is_file($file)) {
            print $file . '<br />';
        } elseif (is_dir($file)) {
            readFileFromDir($file);
        }
    }
}

Call method:


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

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


Related articles: