Skip to content

Instantly share code, notes, and snippets.

@magickatt
Created January 24, 2014 12:24
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save magickatt/8596331 to your computer and use it in GitHub Desktop.
Save magickatt/8596331 to your computer and use it in GitHub Desktop.
Recursively delete the contents of a directory
<?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