PHP Empty folder not deleting with rmdir command

3.9k views Asked by At

My code is as below:

<?php
    header("Location: ../");
    unlink("index.php");
    unlink("style.css");
    unlink("success.php");
    unlink("fail.php");
    unlink("remove.php");
    unlink("README.md");
    unlink(".gitignore");
    unlink(".git");
    rmdir("../Humble-Installer");
    die();

But every time I run it I receive the following error:

[17-Nov-2014 19:47:37 Pacific/Auckland] PHP Warning:  unlink(.git): Operation not permitted in /Users/user/Humble/admin/Humble-Installer/remove.php on line 10
[17-Nov-2014 19:47:37 Pacific/Auckland] PHP Warning:  rmdir(../Humble-Installer): Directory not empty in /Users/user/Humble/admin/Humble-Installer/remove.php on line 11

I have no idea, the directory is empty but will not delete... even if I remove the unlink(."git"); it still throws an error?

Cheers.

2

There are 2 answers

1
krisanalfa On BEST ANSWER

You can use this simple function to delete folder recursively:

function rrmdir($dir) { 
    if (is_dir($dir)) { 
        $objects = scandir($dir); 
        foreach ($objects as $object) { 
            if ($object != "." && $object != "..") { 
                if (filetype($dir."/".$object) == "dir") rrmdir($dir."/".$object); else unlink($dir."/".$object); 
            } 
        }
        reset($objects); 
        rmdir($dir); 
    }
}

Notes:

unlink is for a file, .git is a directory, so it won't remove, use rmdir. If you want to do it recursively, use function I wrote above.

Update

If you want to use RecursiveIteratorIterator, you can use this function:

/**
 * Remove directory recursively.
 *
 * @param string $dirPath Directory you want to remove.
 */
function recursive_rmdir($dirPath)
{
    foreach (new RecursiveIteratorIterator(new RecursiveDirectoryIterator($dirPath, FilesystemIterator::SKIP_DOTS), RecursiveIteratorIterator::CHILD_FIRST) as $path) {
        $pathName = $path->getPathname();

        echo $pathName."\n";

        ($path->isDir() and ($path->isLink() === false)) ? rmdir($pathName) : unlink($pathName);
    }
}
0
Dawood Ikhlaq On

simplest function using glob

function removeDirectory($directory)
{
    $files=glob($directory.'/*');
    foreach ($files as $file)
    {
        if(is_dir($file))
        {
            removeDirectory($file);
            continue;
        }
        unlink($file);
    }
    rmdir($directory); 
}

this function will delete all the files and folders inside the given directory and at the end directory it self.