PHP remove non empty directory

  • 14 July, 2018
  • Renish Khunt
  • PHP

How to remove directory using PHP. We can remove directory using rmdir¬†funciton on PHP. But when we can try to remove non-empty directory using “rmdir” function we got exception/error something like “The directory is not empty.”.

So let’s see how we can remove non-empty directory using PHP. For remove non-empty directory using below function.

function deleteDirectory($dir) {
    if (!file_exists($dir)) {
        return true;
    }

    if (!is_dir($dir)) {
        return unlink($dir);
    }

    foreach (scandir($dir) as $item) {
        if ($item == '.' || $item == '..') {
            continue;
        }

        if (!deleteDirectory($dir . DIRECTORY_SEPARATOR . $item)) {
            return false;
        }

    }

    return rmdir($dir);
}

you can used above function for remove non-empty directory like.

deleteDirectory('folderPath');

You can get more detail about above function from here.

If you face any issue after using this function write the comment below.