【问题标题】:Check if folder is empty outputs error (PHP)检查文件夹是否为空输出错误(PHP)
【发布时间】:2011-06-20 12:57:46
【问题描述】:

我有一个代码来检查目录是否为空,这样我就可以执行操作,但是这个简单的代码给出了一个错误:

警告: opendir(/Site/images/countries/abc/a/2.swf,/Site/images/countries/abc/a/2.swf) [function.opendir]:该系统找不到指定的路径。 (代码:3)在 C:\wamp\www\Site\index.PHP 第 374 行

没有这样的文件

function IsNotEmpty($folder){
$files = array ();
if ( $handle = opendir ( $folder ) ) 
{
  while ( false !== ( $file = readdir ( $handle ) ) )
   {
      if ( $file != "." && $file != ".." ) 
         {
            $files [] = $file;
         }
   }

    closedir ( $handle ); 
 }
 return ( count ( $files ) > 0 ) ? TRUE: FALSE; }



 $dir ="/Site/images/countries/abc/a/2.swf";

 if (IsNotEmpty($dir)==true) 
     {
         echo "There is no such file";
 }
  else
     {
         echo "The file exists!";
     };

我不明白这里有什么问题。文件退出指定目录。

【问题讨论】:

    标签: php dir opendir


    【解决方案1】:

    opendir 用于打开目录,而不是文件 :-)

    您也可以尝试暂时放入调试内容,以便查看发生了什么:

    function IsNotEmpty ($folder) {
        $files = array ();
        if ($handle = opendir ($folder))  {
            echo "DEBUG opened okay ";
            while (false !== ($file = readdir ($handle))) {
                if ( $file != "." && $file != ".." ) {
                    $files [] = $file;
                    echo "DEBUG got a file ";
                }
            }
            closedir ($handle); 
        } else {
            echo "DEBUG cannot open ";
        }
        return (count($files) > 0 ) ? TRUE : FALSE;
    }
    
    $dir ="/Site/images/countries/abc/a";
    if (IsNotEmpty($dir)) { 
        echo "There is no such file";
    } else {
        echo "The file exists!";
    }
    

    如果这仍然不起作用并且您确定目录存在(请记住,大小写对于 UNIX 很重要),您可能需要查看该目录的权限以确保允许尝试访问它的用户 ID。

    【讨论】:

    • 什么意思?我尝试使用$dir ="/Site/images/countries/abc/a/";,但这是同样的错误。
    • @Christine,如果是这种情况,那么您还需要检查权限。
    • @Christine,那么您需要 (1) 检查该目录是否确实存在; (2) 检查用户是否拥有搜索(执行)权限。也许一个快速的检查方法是暂时设置$dir = "/tmp";,因为几乎每个人都应该在那里拥有搜索权限。
    【解决方案2】:

    您应该使用以下 sn-p 作为函数的主体:

    $aFiles = glob($sFolder);
    return (sizeof($aFiles) < 1) true : false;
    

    这会将文件夹的内容作为数组获取,当为空时 - 您的目录为空。

    【讨论】:

      【解决方案3】:

      试试这个:

      function IsNotEmpty($dir) {
            $dir = rtrim($dir, '/').'/';
            return is_dir($dir) && count(glob($dir.'*.*') > 2);
      }
      

      【讨论】:

        【解决方案4】:

        Christine,尝试删除尾部斜杠:

        $dir ="/Site/images/countries/abc/a/"
        

        变成

        $dir ="/Site/images/countries/abc/a"
        

        【讨论】:

          猜你喜欢
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2014-12-16
          • 1970-01-01
          • 2013-03-31
          相关资源
          最近更新 更多