PHP: What is the best and easiest way to check if directory is empty or not [closed]
Asked Answered
N

2

14

I got a root directory with 100s of dynamically generated folders. As time goes some of these folders will need to be extirpated from system on the condition that this(ese) directories(s) must be empty. What would be the best shortest, easiest and/or most effective way to achieve that?

Neap answered 8/9, 2013 at 15:48 Comment(2)
rmdir will fail for non-empty directory, so just $deleted = @rmdir('/path/to/folder');Utility
Thanks... going the glob way as suggested by both @Matteo and JeffmanNeap
J
31

Use glob :

if (count(glob("path/*")) === 0 ) { // empty

A nice thing about glob is that it doesn't return . and .. directories.

Jorin answered 8/9, 2013 at 15:54 Comment(4)
use GLOB_NOSORT flag to increase performanceBrelje
but if ./.. are not reported, then such dir would not be deleted, as it is not empty ... so it seems to be not good for empty dir removalMcgaha
This wrong way, glob() ignores hidden files by default, php.net/manual/ru/function.glob.php#68869 So, if you add the mask to get hidden files in glob() you've got the same solution, as @Matteo wrote below.Eagre
Considering coding convenience this is efficient. Considering performance this may be bad if glob first need to deliver +1000 files for each dir to check after which count tells how many files there are.Xylol
B
8

You can count the items contained in the folder. The first two items are . and .., so just check the items count.

$files_in_directory = scandir('path/to');
$items_count = count($files_in_directory);
if ($items_count <= 2)
{
    $empty = true;
}
else {
    $empty = false;
}
Buckie answered 8/9, 2013 at 15:58 Comment(3)
Is this going to be quicker and most effective way than the glob suggested by @jeffman ?Neap
I benchmarked the two solutions and actually Jeffman one's is faster (on one folder). Jeffman: 5.388E-5 seconds My solution: 2.909E-5 secondsBuckie
+1...for elaborating further. ThanksNeap

© 2022 - 2024 — McMap. All rights reserved.