PHP: Recursively remove a directory and all files and folder contained within

August 22, 2011

The rmdir function of PHP cannot remove a directory if it has anything inside of it, whether it be files or folders. The following method can be used to recursively remove all the files and folders from the directory, and will remove the directory itself. To use it simply copy the code into your application and call rrmdir with the path to the directory you would like to remove.

/**
 * Recursively removes a folder along with all its files and directories
 * 
 * @param String $path 
 */
function rrmdir($path) {
     // Open the source directory to read in files
        $i = new DirectoryIterator($path);
        foreach($i as $f) {
            if($f->isFile()) {
                unlink($f->getRealPath());
            } else if(!$f->isDot() && $f->isDir()) {
                rrmdir($f->getRealPath());
            }
        }
        rmdir($path);
}

7 thoughts on “PHP: Recursively remove a directory and all files and folder contained within

  1. JaredNinja (November 10, 2012)

    This doesn’t remove the folders itself. It removes all files, but the folders are left empty instead of deleted.

  2. JaredNinja (November 10, 2012)

    Adding

    rmdir($f->getRealPath());

    After line 14 fixes it

    So you get:

    function rrmdir($path) {
    // Remove a dir (all files and folders in it)
    $i = new DirectoryIterator($path);
    foreach($i as $f) {
    if($f->isFile()) {
    unlink($f->getRealPath());
    } else if(!$f->isDot() && $f->isDir()) {
    rrmdir($f->getRealPath());
    rmdir($f->getRealPath());
    }
    }
    }

  3. suleman (September 11, 2013)

    Thanks for the help

  4. Mariano (December 26, 2014)

    wow this is the ONLY snippet that recursively deletes files and folders that works! I tested more than 15 code snippet.
    Thank you so much for sharing your knowledge and helping me learn further about manipulating files and directories.

    1. Ben Lobaugh (blobaugh) (December 28, 2014)

      Thank you for the kind words. I am glad my little snippet was able to help you out!

  5. kalyan (October 1, 2015)

    guy’s I tried but not worked…!

    isFile()) {
    unlink($f->getRealPath());
    } else if(!$f->isDot() && $f->isDir()) {
    rrmdir($f->getRealPath());
    rmdir($f->getRealPath());
    }
    }
    }
    ?>

  6. آموزش php (January 1, 2016)

    very very good idea..
    thanks.