递归文件列表功能

时间:2015-01-19 06:59:31

标签: php file recursion directory

我正在尝试编写一个recursive php函数,用于打印其中的目录和文件。我知道我可以使用RecursiveIteratorIterator php,但这不是重点,我只是尝试升级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);
?>

问题是,当我调用此函数时,它进入无限循环,我无法弄清楚原因。

1 个答案:

答案 0 :(得分:0)

我已经测试了你的功能,但它确实有效,但我想提出这些评论:

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