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

2022-01-01 00:00:00 directory php

我正在使用以下脚本读取目录.如果目录中没有文件,它应该显示为空.问题是,即使里面有文件,它也一直说目录是空的,反之亦然.

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 dir_is_empty($dir) {
  $handle = opendir($dir);
  while (false !== ($entry = readdir($handle))) {
    if ($entry != "." && $entry != "..") {
      closedir($handle);
      return false;
    }
  }
  closedir($handle);
  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

表达式在编程语言方面已经返回EmptyNon Empty,分别是falsetrue - 所以,您可以在没有任何中间值的情况下在 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

相关文章