I've got a folder, filled with both empty and full folders.
I want to iterate over all of them, figure out if they are empty, and if so, remove them. I've seen some questions that are appliccable, but I cannot figure out the total solution:
There must be some easy sure-fire way to do this, using the new PHP5 functions?
Something like (pseudocode full of errors)
<?php
$dir = new DirectoryIterator('/userfiles/images/models/');
foreach ($dir as $fileinfo) {
if (!$fileinfo->isDot()) {
if(!(new \FilesystemIterator($fileinfo))->valid()) {
rmdir($fileinfo);
}
}
}
?>
This should work for you:
Here I just get all directory's from a specific path with glob()
(PHP 4 >= 4.3.0, PHP 5). Then I iterate through every directory and check if it is empty.
If it is empty I remove it with rmdir()
else I check if there is another direcotry in it and call the function with the new directory
<?php
function removeEmptyDirs($path, $checkUpdated = false, $report = false) {
$dirs = glob($path . "/*", GLOB_ONLYDIR);
foreach($dirs as $dir) {
$files = glob($dir . "/*");
$innerDirs = glob($dir . "/*", GLOB_ONLYDIR);
if(empty($files)) {
if(!rmdir($dir))
echo "Err: " . $dir . "<br />";
elseif($report)
echo $dir . " - removed!" . "<br />";
} elseif(!empty($innerDirs)) {
removeEmptyDirs($dir, $checkUpdated, $report);
if($checkUpdated)
removeEmptyDirs($path, $checkUpdated, $report);
}
}
}
?>
(PHP 4 >= 4.3.3, PHP 5)
removeEmptyDirs — Removes empty directory's
void removeEmptyDirs( string $path [, bool $checkUpdated = false [, bool $report = false ]] )
The removeEmptyDirs() function goes through a directory and removes every empty directory
path
The Path where it should remove empty directorys
checkUpdated
If it is set to TRUE it goes through each directory again if one directory got removed
report
If it is set to TRUE the function outputs which directory get's removed
None
As an example:
If $checkUpdated
is TRUE
structures like this get's deleted entirely:
- dir
| - file.txt
| - dir
| - dir
Result:
- dir
| - file.txt
If it is FALSE
like in default the result would be:
- dir
| - file.txt
| - dir //See here this is still here
If $report
is TRUE
you get a output like this:
test/a - removed!
test/b - removed!
test/c - removed!
Else you get no output
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With