PHP unlink()错误:“目录不为空”

I have the following recursive method to delete a directory and all its sub-directories and files:

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

On occasion, the get a Warning, "Directory not empty".

The directory is actually created as a temporary holder for files. The files are downloaded from the Internet using the following snippet:

file_put_contents($filename, file_get_contents($file))

After they are downloaded (a write operation), they are then uploaded to a website (a read operation). Once done uploading, the temporary folder and its files are then deleted.

The odd thing is that when I look inside the temporary folder, there are no files there. It's as if the code tried to delete the folder while the last file was in the process of being deleted?

Any ideas what might be wrong and how to resolve it? I need this code to run on Windows and *nix, so a *nix only solution is not an option.

The constant DIRECTORY_SEPARATOR might help you with Windows/Unix compatibility. For the folder not empty, try this:

protected function _rrmdir($dir)
{
    if (is_dir($dir)) {
        $objects = scandir($dir);
        foreach ($objects as $object) {
            if ($object != '.' && $object != '..') {
                if (is_dir($dir . DIRECTORY_SEPARATOR . $object)) {
                    _rrmdir($dir . DIRECTORY_SEPARATOR . $object);
                } else {
                    if( is_file($dir . DIRECTORY_SEPARATOR . $object) ) {
                        if(!unlink($dir . DIRECTORY_SEPARATOR . $object)) {
                            // code in case the file was not removed
                        }
                        // wait a bit here?
                    } else {
                        // code for debug file permission issues
                    }
                }
            }
        }
        reset($objects);
        rmdir($dir);
    }
}

It might happen that you try to remove a file which permissions are not at php exec level.
The is_file() method will return FALSE only if no read permissions, mind that write permissions are needed by the execution owner to delete files.