PHP remove non empty directory

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.

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s