如何使用PHP来检查目录是否为空?

问题描述:

我正在使用以下脚本来读取目录。如果目录中没有文件应该是空的。问题是,即使内部存在ARE文件,它仍然表示目录为空。反之亦然。

I am using the following script to read a directory. If there is no file in the directory it should say empty. The problem is, it just keeps saying the directory is empty even though there ARE files inside and vice versa.

<?php
$pid    =       $_GET["prodref"];
$dir    =       '/assets/'.$pid.'/v';
$q      =       (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';

    if ($q="Empty")
    {

        echo "the folder is empty"; 

    }else{

        echo "the folder is NOT empty";

    }
?>


似乎你需要 scandir 而不是glob,因为glob无法看到unix隐藏文件。

It seems that you need scandir instead of glob, as glob can't see unix hidden files.

<?php
$pid = basename($_GET["prodref"]); //let's sanitize it a bit
$dir = "/assets/$pid/v";

if (is_dir_empty($dir)) {
  echo "the folder is empty"; 
}else{
  echo "the folder is NOT empty";
}

function is_dir_empty($dir) {
  if (!is_readable($dir)) return NULL; 
  return (count(scandir($dir)) == 2);
}
?>

请注意,此代码不是效率的最高峰,因为无需将所有文件仅读取到告诉目录是否为空。所以,更好的版本将是

Note that this code is not the summit of efficiency, as it's unnecessary to read all the files only to tell if directory is empty. So, the better version would be

function is_dir_empty($dir) {
  if (!is_readable($dir)) return NULL; 
  $handle = opendir($dir);
  while (false !== ($entry = readdir($handle))) {
    if ($entry != "." && $entry != "..") {
      return FALSE;
    }
  }
  return TRUE;
}

顺便说一句,请勿使用 替换布尔值值。后者的目的是告诉你有没有空的东西。一个

By the way, do not use words to substitute boolean values. The very purpose of the latter is to tell you if something empty or not. An

a === b

表达式已经返回非空根据编程语言 FALSE 或 TRUE - 所以可以在控件结构中使用结果,如 IF() 没有任何中间值

expression already returns Empty or Non Empty in terms of programming language, FALSE or TRUE respectively - so, you can use the very result in control structures like IF() without any intermediate values