2009-07-04 96 views
1

我试图编写一个脚本来列出目录和子目录中的所有文件,等等。如果我不包括检查是否有任何文件是目录,脚本工作正常。该代码不会生成错误,但会生成一百行文字,说明“目录列表”。而不是我期待的。任何想法为什么这不起作用?PHP目录列表代码故障

<?php 

//define the path as relative 
$path = "./"; 

function listagain($pth) 
{ 
//using the opendir function 
$dir_handle = @opendir($pth) or die("Unable to open $pth"); 

echo "Directory Listing of $pth<br/>"; 

//running the while loop 
while ($file = readdir($dir_handle)) 
{ 
    //check whether file is directory 
    if(is_dir($file)) 
    { 
     //if it is, generate it's list of files 
     listagain($file); 
    } 
    else 
    { 
     if($file!="." && $file!="..") 
     echo "<a href='$file'>$file</a><br/>"; 
    } 
} 
//closing the directory 
closedir($dir_handle); 
} 

listagain($path) 

?> 

回答

4

第一个实体...分别指当前和父目录。所以你得到一个无限递归。

你应该检查文件类型之前先检查是否有:

if ($file!="." && $file!="..") { 
    if (is_dir($file)) { 
     listagain($file); 
    } else { 
     echo '<a href="'.htmlspecialchars($file).'">'.htmlspecialchars($file).'</a><br/>'; 
    } 
} 
1

问题是,变量$file只包含路径的基名。所以,你需要使用$pth.$file