Cannot delete folder using with rmdir function

392 Views Asked by At

I have a problem deleting the selected folder in the folder path. I am using XAMPP, and won't delete the selected folder path is C:\xampp\htdocs\delete_folder\test\abc, but the below coding is cannot work to delete the folder. I think because inside the abc folder got another folder.

I am referring to this link to do the rmdir function: https://www.php.net/manual/zh/function.rmdir.php

Below is a sample coding in the index.php, that mean every time I am refreshing the page, if work it can delete the selected folder:

<?php
$dir ="test/abc";
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);
}
?>

Hope someone can guide me on how to solve this problem. Thanks.

2

There are 2 best solutions below

2
RufusVS On BEST ANSWER

The way your code is written, are you expecting the line:

$dir ="test/abc";

To pass the name test/abc to your function that starts with:

function deleteDirectory($dir) {

and execute the function? That is not the way functions work.

The $dir is a function argument and has absolutely no relationship with the $dir you defined just before it. Your code should look more like:

<?php

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

deleteDirectory("test/abc");

?>

See? The function is defined, then it gets call with the desired argument. (I hope my php syntax is correct here, I rarely use php. But the general idea is the same in all languages)

0
brombeer On

The Windows shell/cmd has a command rmdir that can remove folders with content. Use

exec('rmdir FOLDERNAME /s /q');

Open a shell/cmd on Windows and type rmdir /? and you'll see an explanation of the parameters:

/s removes folders with content inside

/q won't ask for confirmation.

Use with caution!