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

标签 php directory

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

<?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 隐藏文件。

<?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);
}
?>

请注意,这段代码并不是效率的顶峰,因为不需要读取所有文件来判断目录是否为空。所以,更好的版本应该是

function dir_is_empty($dir) {
  $handle = opendir($dir);
  while (false !== ($entry = readdir($handle))) {
    if ($entry != "." && $entry != "..") {
      closedir($handle);
      return false;
    }
  }
  closedir($handle);
  return true;
}

顺便说一句,不要使用 words 代替 boolean 值。后者的目的是告诉您某物是否为空。一个

a === b

表达式在编程语言方面已经返回 EmptyNon Empty,分别为 falsetrue - 所以,您可以在 IF() 等控制结构中使用结果,而无需任何中间值

关于php - 如何使用 PHP 检查目录是否为空?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7497733/

相关文章:

php - 具有多个数据库的 Yii 迁移 - 指定 DB?

php - 通过 DOM 或 XPATH 获取每个元素属性的宽度和高度

c - 如何知道在 OS/X 中启动可执行文件的目录?

file - 实现文件系统的基础

java - 将 Netbeans 项目移至 Windows 10 家庭版

python - 尝试将目录列表输出到 csv 文件

php - SphinxQL-查询生成器。 PHP 警告 : Packets out of order. 预计收到 0 1。数据包大小=0

php - 如何计算查询 PHP MySQL 中的行?

PHP,命名空间中的新变量类

linux - Bash 脚本 : Find all filetypes and paths