DZone Snippets is a public source code repository. Easily build up your personal collection of code snippets, categorize them with tags / keywords, and share them with the world

Snippets has posted 5883 posts at DZone. View Full User Profile

RemoveDir //PHP Function

08.20.2006
| 7047 views |
  • submit to reddit
        Removes a folder, including its subfolders and files in a efficient way without recursion, returns Boolean.

//+ Jonas Raoni Soares Silva
//@ http://jsfromhell.com

function removeFolder($dir){
	if(!is_dir($dir))
		return false;
	for($s = DIRECTORY_SEPARATOR, $stack = array($dir), $emptyDirs = array($dir); $dir = array_pop($stack);){
		if(!($handle = @dir($dir)))
			continue;
		while(false !== $item = $handle->read())
			$item != '.' && $item != '..' && (is_dir($path = $handle->path . $s . $item) ?
			array_push($stack, $path) && array_push($emptyDirs, $path) : unlink($path));
		$handle->close();
	}
	for($i = count($emptyDirs); $i--; rmdir($emptyDirs[$i]));
}