如何使用PHP检查目录是否为空? [英] How can I use PHP to check if a directory is empty?

查看:77
本文介绍了如何使用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 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 值.后者的目的是告诉您是否有空.

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

表达式已经分别以编程语言FALSETRUE的形式返回EmptyNon Empty-因此,您可以将结果直接用于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

这篇关于如何使用PHP检查目录是否为空?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆