Search code examples
phpfilesystemsdirectoryunlinkrmdir

Delete Directory and directories inside


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?


Solution

  • 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
    }
    
    ?>