0

I want to delete a directory and all it's subdirectories.

$folders('users','users/100282','users/100282/test');
array_map("rmdir",array_reverse($folders));

Unfortunately this doesn't work. I get 2 errors saying that the directory is not empty. If i refresh, only 1 error, if I refresh once more, no more errors.


What's happening is that the script attempts to remove the parent directory before the previous task is ececuted, which renders the folder non-empty. How do I fix this?

Nicky Smits
  • 2,980
  • 4
  • 20
  • 27

1 Answers1

2

How abouts something like this using RecursiveIteratorIterator:

<?php 
/**
 * Recursive directory remover.
 *
 * @param string $dir
 * @return bool
 */
function destroy_dir($dir) {
    foreach(new RecursiveIteratorIterator(
                new RecursiveDirectoryIterator($dir, FilesystemIterator::SKIP_DOTS),
                RecursiveIteratorIterator::CHILD_FIRST) as $path) {

        //remove file or folder
        $path->isFile() ? unlink($path->getPathname()) : rmdir($path->getPathname());
    }
    return rmdir($dir);
}

//usage
$dir = './users';
//checks
if(is_dir($dir)){
    //call
    if(destroy_dir($dir)){
        //directory removed
    }else{
        //error removing directory
    }
}else{
    //users directory not found
}

?>
Lawrence Cherone
  • 46,049
  • 7
  • 62
  • 106
  • It works like a charm. How does it iterate through the directory though? Does CHILD_FIRST tell the iterator it should begin in the lowest directories possible? – Nicky Smits Mar 17 '14 at 22:16
  • Excellent! THX! I added a small line of code to check whether the directory exists (I misspelled the dir_name accidentally and it threw warnings). Might be a nice addition. – Nicky Smits Mar 17 '14 at 22:21
  • Yeah that should be done on the root dir before calling the function, not within the function as it could confuse parent code if checking for bool, fyi: you can find out lots of info about the iterator class here, more then I could explain, http://stackoverflow.com/questions/12077177/how-does-recursiveiteratoriterator-work-in-php hope it helps. – Lawrence Cherone Mar 17 '14 at 22:24
  • @NickySmits check update, do checks before calling it, the function returns bool, if you do it in the function then you wont be able to differentiate between the dir not found or some permission issue ect. good luck – Lawrence Cherone Mar 17 '14 at 22:31