PHP: Recursive directory removal
<?php
/**
* Recursively removes a directory.
*
* @param string $path Directory path to remove.
* @param bool $suicide Whether to remove itself or not.
*
* @return void
*/
function rmdir_recursive($path, $suicide = TRUE)
{
static $self;
isset($self) OR $self = $path;
$result = FALSE;
$iterator = new DirectoryIterator($path);
// Recurse into the path
foreach ($iterator as $item)
{
// Remove if it's a file
$item->isFile() AND unlink($item->getRealPath());
// Go deep Chandler, go!
if ( ! $item->isDot() AND $item->isDir())
{
rmdir_recursive($item->getRealPath());
}
}
// Remove child dirs. Source dir (initial $path) will
// be removed only if it's a suicidal function call!
if ($suicide OR realpath($self) != realpath($path))
{
rmdir($path);
}
}