Remove empty subfolders with PHP

后端 未结 6 1370
小鲜肉
小鲜肉 2020-12-09 22:38

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

6条回答
  •  没有蜡笔的小新
    2020-12-09 23:02

    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
    

提交回复
热议问题