【问题标题】:File are shown but not directories显示文件但不显示目录
【发布时间】:2014-10-22 04:22:37
【问题描述】:

所以这段代码做了它应该列出目录中的文件..但它也显示了目录..我想删除它.​​.使用 scandir 错误吗?

    <ul>
<?php echo "List of files"?>
<?php
$dir = 'kcfinder/upload/files';
$files = scandir($dir);

foreach($files as $ind_file){
?>

<li><?php echo $ind_file;?> </a> | <a href="includes/delete.php?file=<?=$ind_file?>">Delete</a></li>
<?php
}
?>
</ul>

【问题讨论】:

    标签: php directory scandir


    【解决方案1】:

    使用is_file函数,可以检查当前项是否为文件。

    试试这个代码

    if(is_file($dir . $ind_file)) {
     // You code
    }
    

    【讨论】:

      【解决方案2】:

      使用if(is_dir($ind_file)) 获取目录,使用if (is_file($ind_file)) 获取文件

      $full_path = "kcfinder/upload/files";
      
      if ($handle = opendir("$full_path")) 
      { 
          while (false !== ($file = readdir($handle))) 
          { 
              if(is_dir($full_path."/".$file))
              {
                  if($file!='..' && $file!='.')
                  {               
                   //for folders  
                  } 
             }else
             {
                //for files
             }
          }
      } 
      

      【讨论】:

      • 首先,你应该使用is_file()scandir();此外,如果可以避免的话,切勿将函数调用放在 while 语句中。
      • 感谢您的评论,但我已将它用于我自己的文件管理器,我没有任何问题。你是说我使用了错误的代码?
      • 是的,它有效,但这是一种糟糕的编码习惯。它鼓励冗余编码并浪费资源。请参阅我对您的答案所做的编辑,了解正确的做法。
      • 糟糕!好的,我会改进我的代码,只要我对它们没有任何问题。
      【解决方案3】:
      <ul>
      <?php echo "List of files"?>
      <?php
      $dir = 'kcfinder/upload/files';
      $files = scandir($dir);
      
      foreach($files as $ind_file=>$afile){
        if($ind_file!=0 & $ind_file!=1){ // skip '.' and '..'
      ?>
      <li><?php echo $afile;?> </a> | <a href="includes/delete.php?file=<?=$afile?>">Delete</a></li>
      <?php
        }
      }
      ?>
      </ul>
      

      【讨论】:

        【解决方案4】:

        您应该在 foreach 语句中使用 is_file()

        像这样:

        $dir = 'kcfinder/upload/files';
        $files = scandir($dir);
        
        foreach ($files as $ind_file) {
          if (is_file(__DIR__.'/'.$ind_file)) {
            ?>
            <li><?php echo $ind_file;?> </a> | <a href="includes/delete.php?file=<?=$ind_file?>">Delete</a></li>
            <?php
          }
        }
        

        【讨论】:

          猜你喜欢
          • 2017-03-13
          • 1970-01-01
          • 2021-06-08
          • 1970-01-01
          • 2013-07-19
          • 1970-01-01
          • 2014-09-17
          • 1970-01-01
          • 2012-01-21
          相关资源
          最近更新 更多