2013-09-29 41 views
0

我有一個腳本文件。列出目錄中的文件和文件夾..我想隱藏某些文件和文件夾。我怎麼做?如何從目錄中的列表中隱藏文件

<?php 
if ($handle = opendir('.')) { 
    while (false !== ($file = readdir($handle))) 
    { 
     if (($file != ".") 
     && ($file != "..")) 
     { 
      $thelist .= '<LI><a href="'.$file.'">'.$file.'</a>'; 
     } 
    } 

    closedir($handle); 
} 
?> 

<P>List of files:</p> 
<UL> 
<P><?=$thelist?></p> 
</UL> 
+1

您是否事先知道文件的名稱? –

回答

0
<?php 
$files_to_hide = array('file1.txt', 'file2.txt'); 
if ($handle = opendir('.')) { 
    while (false !== ($file = readdir($handle))) 
    { 
     if (($file != ".") && ($file != "..") && !in_array($file, $files_to_hide)) 
     { 
      $thelist .= '<LI><a href="'.$file.'">'.$file.'</a>'; 
     } 
    } 

    closedir($handle); 
} 
?> 

<P>List of files:</p> 
<UL> 
<P><?=$thelist?></p> 
</UL> 
+0

是否有任何具體的理由不將''。''和'「..」'添加到'$ file_to_hide'數組中? – hakre

+0

當然,如果需要,這是可能的。 –

0

將要排除的文件名列表放入數組中。

之後,檢查是否將文件名exists in the array添加到$thelist之前。

您可以添加它作爲if()語句的一部分,該語句檢查文件名是.還是..

0

事情是這樣的:

<?php 
$bannedFiles = Array(".", "..", "example"); 
if ($handle = opendir('.')){ 
    while (false !== ($file = readdir($handle))) 
    { 
     $banned = false; 
     foreach ($bannedFiles as $bFile){ 
      if ($bFile == $file){ 
       $banned = true; 
      } 
     } 
     if (!$banned){ 
      $thelist .= '<LI><a href="'.$file.'">'.$file.'</a></LI>'; 
     } 
    } 

    closedir($handle); 
} 
?> 

<P>List of files:</p> 
<UL> 
<P><? echo $thelist;?></p> 
</UL> 
0

如果你知道你要隱藏的文件/目錄的名稱,就可以保持這樣的條目的設定圖,內它們過濾掉while循環。

貴定地圖是這樣的:

$items_to_hide = [ "/home/me/top_secret" => 1, "/home/me/passwords.txt" => 1, ... ] 

然後你會modfiy while循環是這樣的:

while (false !== ($file = readdir($handle))) 
{ 
    // check map if said file is supposed to be hidden, if so skip current loop iteration 
    if($items_to_hide[$file]) { 
     continue; 
    } 
    if (($file != ".") 
    && ($file != "..")) 
    { 
     $thelist .= '<LI><a href="'.$file.'">'.$file.'</a>'; 
    } 
} 

希望這有助於。

編輯:

也想提一下,使用PHP的有序排列的「黑名單」是相當有效的,作爲一個單一的查詢會出現在幾乎恆定的時間。因此,您可以根據自己的需要增加黑名單,並且仍然可以看到不俗的表現。

相關問題