2013-09-29 115 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的有序排列的“黑名单”是相当有效的,作为一个单一的查询会出现在几乎恒定的时间。因此,您可以根据自己的需要增加黑名单,并且仍然可以看到不俗的表现。

相关问题