PHP remove non-empty directory programmatically

0

Today, We are going to learn PHP to remove non-empty directory. PHP provides rmdir function using that we can easily remove any directory. But When you are going to remove a non-empty directory using rmdir it’s fire exception. You can’t able to remove non-empty directory message something like The directory is not empty.

PHP remove non-empty directory

So Let’s see, how we can remove a non-empty directory. I am going to share function with you using that function you can able to remove a non-empty directory.

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);
}

First of all, Place this function with your code. Now, you just need to pass the directory path as a parameter to deleteDirectory function like.

deleteDirectory('folderPath');

Finally, Now you can able to remove a non-empty directory. You can get more detail about this function from here.

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

Share.

Leave A Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.