2009-07-04 18 views
1

ディレクトリやサブディレクトリ内のすべてのファイルを一覧表示するスクリプトを作成しようとしました。ファイルがディレクトリであるかどうかをチェックしません。コードはエラーを生成しませんが、 "Directory Listing of。"というテキストを100行生成します。私が期待していたものの代わりに。なぜこれがうまくいかないのか?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を使用する必要があります。