Skip to content

Instantly share code, notes, and snippets.

@sepehr
Last active July 9, 2018 00:52
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save sepehr/5726506 to your computer and use it in GitHub Desktop.
Save sepehr/5726506 to your computer and use it in GitHub Desktop.
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);
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment