0

I'm using the following function to delete all files and subfolders from a folder, before removing the folder itself:

public function deleteDownload($dir): void
{
    foreach(glob($dir . '/{,.}[!.,!..]*',GLOB_MARK|GLOB_BRACE) as $file) {

        if(is_dir($file)) {
            $this->deleteDownload($file);
        }
        else {
            unlink($file);
        }
    }
    rmdir($dir);
}

This works great, until the program stumbles upon a directory with braces in the name, e.g: {test}. When this happens, the program throws an exception saying that the directory is not empty, which is correct as it contains files that should have been deleted:

ErrorException rmdir(/Users/xx/xx/xx/xx/xx/storage/app/c544946e914f/test//{test}/): Directory not empty

When I rename the filename from {test} to test everything works as expected.

Can someone explain to me why this happens and how to fix this?

user3478148
  • 433
  • 1
  • 8
  • 26
  • Alternative approaches can be found in https://stackoverflow.com/questions/3338123/how-do-i-recursively-delete-a-directory-and-its-entire-contents-files-sub-dir – Nigel Ren Apr 29 '21 at 14:12
  • @NigelRen Yes, thank you, the accepted solution works. But I'm curious why that works while this doesn't. – user3478148 Apr 29 '21 at 14:16
  • That is the reason why I put that as a comment rather than close it as a duplicate. It is useful to sometimes to understand what is going on in any solution. – Nigel Ren Apr 29 '21 at 14:17

0 Answers0