PHP remove non-empty directory using Window Command.

PHP remove non-empty directory using exec windows command. On window operating system when we try to remove non-empty directory every time we get the “directory is not empty.” message when we try to remove directory using PHP.

Let’s see how we can remove non-empty directory using exec window command.

exec(‘attrib -r -a -s -h folderpath /s /d’);
exec(‘rd /s /q folderpath’);

Using above exec command we can remove the non-empty directory.

If you face any issue after using this code please write comment below.

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.