Last active
July 9, 2018 00:52
-
-
Save sepehr/5726506 to your computer and use it in GitHub Desktop.
PHP: Recursive directory removal
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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