Skip to content

Instantly share code, notes, and snippets.

@lutsen
Created April 19, 2015 13:12
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 lutsen/269dcb842c7163ef5ff7 to your computer and use it in GitHub Desktop.
Save lutsen/269dcb842c7163ef5ff7 to your computer and use it in GitHub Desktop.
Remove a directory and it's contents.
<?php
function removeDir($path) {
// Add trailing slash to $path if one is not there
if (substr($path, -1, 1) != "/") {
$path .= "/";
}
$normal_files = glob($path . "*");
$hidden_files = glob($path . "\.?*");
$all_files = array_merge($normal_files, $hidden_files);
foreach ($all_files as $file) {
# Skip pseudo links to current and parent dirs (./ and ../).
if (preg_match("/(\.|\.\.)$/", $file))
{
continue;
}
if (is_file($file) === TRUE) {
// Remove each file in this Directory
unlink($file);
echo "Removed File: " . $file . "<br>";
}
else if (is_dir($file) === TRUE) {
// If this Directory contains a Subdirectory, run this Function on it
removeDir($file);
}
}
// Remove Directory once Files have been removed (If Exists)
if (is_dir($path) === TRUE) {
rmdir($path);
echo "<br>Removed Directory: " . $path . "<br><br>";
}
}
// To remove a dir:
removeDir('/path/to/directory');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment