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?
PHP: What is the best and easiest way to check if directory is empty or not [closed]
Use glob
:
if (count(glob("path/*")) === 0 ) { // empty
A nice thing about glob
is that it doesn't return .
and ..
directories.
use
GLOB_NOSORT
flag to increase performance –
Brelje 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 removal –
Mcgaha
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
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;
}
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 seconds
–
Buckie +1...for elaborating further. Thanks –
Neap
© 2022 - 2024 — McMap. All rights reserved.
rmdir
will fail for non-empty directory, so just$deleted = @rmdir('/path/to/folder');
– Utilityglob
way as suggested by both @Matteo and Jeffman – Neap