skip to Main Content

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 == '..') {

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


    return rmdir($dir);

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


You can get more detail about above function from here.

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


I am a web designer and developer part-time blogger. Write something on some free time. Find my every day thought here :)

Leave a Reply

Your email address will not be published. Required fields are marked *

Back To Top