递归文件列表函数

Recursive Files list function

我正在尝试编写一个 recursive php 函数来打印其中的目录和文件。我知道我可以使用 phpRecursiveIteratorIterator 但这不是重点,我只是想在 recursive functions 中提升我的技能所以这是我当前的代码:

<?php
function recursiveDir($adr){
    $dh  = opendir($adr);
    while (false !== ($filename = readdir($dh))) {
        if(is_dir($adr.'/'.$filename)&& $filename!='.' && $filename!='..'){         
            recursiveDir($adr.'/'.$filename);
        } elseif($filename!='.' && $filename!='..') {
            echo $filename.'<br>';
        }
    }
}
$dir = getcwd();
recursiveDir($dir);
?>

问题是当我调用这个函数时,它进入了一个无限循环,我不知道为什么。

我已经测试了你的功能,它可以工作,但我想提出这些评论:

<?php
/**
  * @param String $adr
  * @param Integer $depth : to show nicely the tree
  */
function recursiveDir($adr, $depth = 0) {
    $depth++;
    $dh  = opendir ($adr);

    if(is_null($dh)) {
        printf ("Can not open this directory %s (may be permission is denied)", $adr);
        return NULL;
    }
    // use upper case for TRUE, FALSE and NULL : PHP recommendation   
    while (FALSE !== ($filename = readdir ($dh))) {
        // it will be easy for another developer what do you want to escape from execution
        if ($filename == '.' || $filename == '..') {
            continue;
        }

        if (is_dir ($adr.'\'.$filename)) {         
            // use printf instead of echo or print, it lets separating between variables and the formatted message            
            printf ("%s DIR: %s.\n", str_repeat ("-", $depth), $adr . '\' . $filename);
            recursiveDir ($adr . '\' . $filename);
        } elseif (is_file ($adr.'\'.$filename)) {
            printf ("%s FILE: %s.\n", str_repeat ("-", $depth + 4), $adr.'\'.$filename); 
        // ALWAYS : write/do something in uncatched cases ...
        } else {
            printf ("Unknown Resource: %s\n", $adr . '\' . $filename);
        }
    }
    // never forget to close an opened resource
    closedir ($dh);
}
$dir = getcwd();
recursiveDir($dir);