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);
}
This doesn’t remove the folders itself. It removes all files, but the folders are left empty instead of deleted.
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());
}
}
}
Thanks for the help
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.
Thank you for the kind words. I am glad my little snippet was able to help you out!
guy’s I tried but not worked…!
isFile()) {
unlink($f->getRealPath());
} else if(!$f->isDot() && $f->isDir()) {
rrmdir($f->getRealPath());
rmdir($f->getRealPath());
}
}
}
?>
very very good idea..
thanks.