PHP – Delete folder

In php, rmdir() is used to delete an empty folder. If the folder has files or sub folders, rmdir command would fail.

This deleteDir function would use recursive approach to do the magic.

function deleteDir($dirPath) {
    if (! is_dir($dirPath)) {
        throw new InvalidArgumentException("$dirPath must be a directory");
    }
    if (substr($dirPath, strlen($dirPath) - 1, 1) != '/') {
        $dirPath .= '/';
    }
    $files = glob($dirPath . '*', GLOB_MARK);
    foreach ($files as $file) {
        if (is_dir($file)) {
            $deleteDir($file);
        } else {
            unlink($file);
        }
    }
    rmdir($dirPath);
}

 381 total views

Author: Albert

Leave a Reply