Back to blog

Recursive remove directory (RMDIR) in PHP

This small php function is a recursive remove directory that remove non empty dirs recursively. It enters every directory, removes…

This small php function is a recursive remove directory that remove non empty dirs recursively. It enters every directory, removes every file starting from the given path.

function rmdir_recurse($path) {
	$path = rtrim($path, '/').'/';
	$handle = opendir($path);
	while(false !== ($file = readdir($handle))) {
		if($file != '.' and $file != '..' ) {
			$fullpath = $path.$file;
			if(is_dir($fullpath)) rmdir_recurse($fullpath); else unlink($fullpath);
		}
	}
	closedir($handle);
	rmdir($path);
}

Canonical URL