I am working on a PHP function that will recursively remove all sub-folders that contain no files starting from a given absolute path.
Here is the code developed so
Solution for Linux, using command line tool but faster and simpler than with pure PHP
/**
* Remove all empty subdirectories
* @param string $dirPath path to base directory
* @param bool $deleteBaseDir - Delete also basedir if it is empty
*/
public static function removeEmptyDirs($dirPath, $deleteBaseDir = false) {
if (stristr($dirPath, "'")) {
trigger_error('Disallowed character `Single quote` (\') in provided `$dirPath` parameter', E_USER_ERROR);
}
if (substr($dirPath, -1) != '/') {
$dirPath .= '/';
}
$modif = $deleteBaseDir ? '' : '*';
exec("find '".$dirPath."'".$modif." -empty -type d -delete", $out);
}
If you need Windows support, use PHP_OS constant and this one-liner
for /f "delims=" %d in ('dir /s /b /ad ^| sort /r') do rd "%d"`enter code here