如何使用 PHP 检查目录是否为空?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/7497733/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How can I use PHP to check if a directory is empty?
提问by TheBlackBenzKid
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";
?>
回答by Your Common Sense
It seems that you need scandir
instead of glob, as glob can't see unix hidden files.
似乎您需要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);
}
?>
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 wordsto substitute booleanvalues. The very purpose of the latter is to tell you if something empty or not. An
顺便说一句,不要使用单词来替换布尔值。后者的真正目的是告诉您某些东西是否为空。一个
a === b
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
表达式已经返回Empty
或Non Empty
在编程语言方面,FALSE
或TRUE
分别 - 因此,您可以在控制结构中使用结果,例如IF()
没有任何中间值
回答by flu
I think using the FilesystemIteratorshould be the fastest and easiest way:
我认为使用FilesystemIterator应该是最快和最简单的方法:
// PHP 5 >= 5.3.0
$iterator = new \FilesystemIterator($dir);
$isDirEmpty = !$iterator->valid();
Or using class member access on instantiation:
或者在实例化时使用类成员访问:
// PHP 5 >= 5.4.0
$isDirEmpty = !(new \FilesystemIterator($dir))->valid();
This works because a new FilesystemIterator
will initially point to the first file in the folder - if there are no files in the folder, valid()
will return false
. (see documentation here.)
这是有效的,因为 newFilesystemIterator
最初将指向文件夹中的第一个文件 - 如果文件夹中没有文件,valid()
将返回false
. (请参阅此处的文档。)
As pointed out by abdulmanov.ilmir, optionally check if the directory exists before using the FileSystemIterator
because otherwise it'll throw an UnexpectedValueException
.
正如 abdulmanov.ilmir 所指出的,在使用之前可以选择检查目录是否存在,FileSystemIterator
否则它会抛出一个UnexpectedValueException
.
回答by Frank
I found a quick solution
我找到了一个快速解决方案
<?php
$dir = 'directory'; // dir path assign here
echo (count(glob("$dir/*")) === 0) ? 'Empty' : 'Not empty';
?>
回答by Toto
use
用
if ($q == "Empty")
instead of
代替
if ($q="Empty")
回答by Robik
Probably because of assignment operator in if
statement.
可能是因为if
语句中的赋值运算符。
Change:
改变:
if ($q="Empty")
To:
到:
if ($q=="Empty")
回答by narfie
This is a very old thread, but I thought I'd give my ten cents. The other solutions didn't work for me.
这是一个非常古老的线程,但我想我会给我的十美分。其他解决方案对我不起作用。
Here is my solution:
这是我的解决方案:
function is_dir_empty($dir) {
foreach (new DirectoryIterator($dir) as $fileInfo) {
if($fileInfo->isDot()) continue;
return false;
}
return true;
}
Short and sweet. Works like a charm.
简短而甜蜜。奇迹般有效。
回答by Wilt
For a object oriented approach using the RecursiveDirectoryIterator
from the Standard PHP Library (SPL).
对于使用一个面向对象的方法RecursiveDirectoryIterator
从标准PHP库(SPL) 。
<?php
namespace My\Folder;
use RecursiveDirectoryIterator;
class FileHelper
{
/**
* @param string $dir
* @return bool
*/
public static function isEmpty($dir)
{
$di = new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS);
return iterator_count($di) === 0;
}
}
No need to make an instance of your FileHelper
whenever you need it, you can access this static method wherever you need it like this:
无需在需要时创建实例FileHelper
,您可以在任何需要的地方访问此静态方法,如下所示:
FileHelper::isEmpty($dir);
The FileHelper
class can be extended with other useful methods for copying, deleting, renaming, etc.
的FileHelper
类可以与用于复制,删除,重命名等其他有用的方法被扩展
There is no need to check the validity of the directory inside the method because if it is invalid the constructor of the RecursiveDirectoryIterator
will throw an UnexpectedValueException
which that covers that part sufficiently.
不需要检查方法内目录的有效性,因为如果它无效, 的构造函数RecursiveDirectoryIterator
将抛出一个UnexpectedValueException
足以覆盖该部分的 。
回答by Drmzindec
Try this:
尝试这个:
<?php
$dirPath = "Add your path here";
$destdir = $dirPath;
$handle = opendir($destdir);
$c = 0;
while ($file = readdir($handle)&& $c<3) {
$c++;
}
if ($c>2) {
print "Not empty";
} else {
print "Empty";
}
?>
回答by André Fiedler
@ Your Common Sense
@你的常识
I think your performant example could be more performant using strict comparison:
我认为您的高性能示例可以使用严格比较来提高性能:
function is_dir_empty($dir) {
if (!is_readable($dir)) return null;
$handle = opendir($dir);
while (false !== ($entry = readdir($handle))) {
if ($entry !== '.' && $entry !== '..') { // <-- better use strict comparison here
closedir($handle); // <-- always clean up! Close the directory stream
return false;
}
}
closedir($handle); // <-- always clean up! Close the directory stream
return true;
}
回答by Alessandro.Vegna
Just correct your code like this:
只需像这样更正您的代码:
<?php
$pid = $_GET["prodref"];
$dir = '/assets/'.$pid.'/v';
$q = count(glob("$dir/*")) == 0;
if ($q) {
echo "the folder is empty";
} else {
echo "the folder is NOT empty";
}
?>