2009-07-04 89 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