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