2010-03-10 47 views
1

我創建了一個腳本,列出目錄,在當前目錄PHP列出目錄,並刪除..和

<?php 
    $dir = getcwd(); 
    if($handle = opendir($dir)){ 
     while($file = readdir($handle)){ 
      if(is_dir($file)){ 
      echo "<a href=\"$file\">$file</a><br />"; 
      } 
     } 
?> 

但問題是,我看到這個「..」和「」正好在目錄列表的上方,當有人點擊它時,他們會被重定向到目錄的一級。有人可以告訴我如何刪除這些「..」和「。」。 ?

回答

8

如果使用執行opendir/readdir的/ closedir功能,您必須手動檢查:

<?php 
if ($handle = opendir($dir)) { 
    while ($file = readdir($handle)) { 
     if ($file === '.' || $file === '..' || !is_dir($file)) continue; 
     echo "<a href=\"$file\">$file</a><br />"; 
    } 
} 
?> 

如果你想使用DirectoryIterator,有isDot()方法:

<?php 
$iterator = new DirectoryIterator($dir); 
foreach ($iterator as $fileInfo) { 
    if ($fileInfo->isDot() || !$fileInfo->isDir()) continue; 
    $file = $fileinfo->getFilename(); 
    echo "<a href=\"$file\">$file</a><br />"; 
} 
?> 

注意:我認爲繼續可以通過減少縮進級別來簡化這種循環。

+0

哈哈。很酷,謝謝你,先生! – sasori 2010-03-10 10:40:54

2
<?php 
    if($handle = opendir($dir)){ 
     while($file = readdir($handle)){ 
      if(is_dir($file) && $file !== '.' && $file !== '..'){ 
      echo "<a href=\"$file\">$file</a><br />"; 
      } 
     } 
    } 
?> 
+0

謝謝先生,不錯的替代品 – sasori 2010-03-10 10:41:16

2

跳過所有隱藏的 「點目錄」:

while($file = readdir($handle)){ 
    if (substr($file, 0, 1) == '.') { 
     continue; 
    } 

跳過點目錄:

while($file = readdir($handle)){ 
    if ($file == '.' || $file == '..') { 
     continue; 
    } 
+0

ah.thank你先生 – sasori 2010-03-10 10:51:54

3

或者使用glob

foreach(glob('/path/*.*') as $file) { 
    printf('<a href="%s">%s</a><br/>', $file, $file); 
} 

如果你的文件,不要」 t遵循名點擴展圖案,使用

array_filter(glob('/path/*'), 'is_file') 

得到的陣列(非隱藏的)唯一的文件名。

+0

感謝您也:) – sasori 2010-03-10 10:52:14