Created
January 24, 2014 12:24
-
-
Save magickatt/8596331 to your computer and use it in GitHub Desktop.
Recursively delete the contents of a directory
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 | |
/** | |
* Delete the contents of a directory (recursively by default) | |
* @todo Handle recursion when calls return false | |
* @param string $path Path to the directory | |
* @param boolean $recursive Whether to delete recursively (true by default) | |
* @return boolean Success or failure | |
*/ | |
function deleteDirectoryContents($path, $recursive = true) | |
{ | |
// Mutually-exclusive flags | |
$isFile = is_file($path); | |
$isDir = is_dir($path); | |
// If the path does not point to a file or directory, do nothing | |
if (! $isFile && ! $isDir) { | |
return false; | |
} | |
// If the path is a file, delete it | |
if ($isFile && ! $isDir) { | |
unlink ($path); | |
return true; | |
} | |
foreach (scandir($path) as $item) { | |
// Ignore *nix current and previous directories | |
if ($item == '.' || $item == '..') { | |
continue; | |
} | |
// If path is a directory, delete the contents of that directory first | |
if (is_dir($item)) { | |
deleteDirectoryContents($item); | |
} | |
// Delete the file/directory | |
unlink($path . DIRECTORY_SEPARATOR . $item); | |
} | |
return true; | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment