Skip to content

Instantly share code, notes, and snippets.

@tsprates
Last active April 19, 2022 22:41
Show Gist options
  • Save tsprates/4f1e821a85e197477cf082b624c34e2c to your computer and use it in GitHub Desktop.
Save tsprates/4f1e821a85e197477cf082b624c34e2c to your computer and use it in GitHub Desktop.
Remove all files and subdirectories from a specific directory.
<?php
/**
* Remove all files and subdirectories from a specific directory (recursively).
*
* @param string $dir The directory to be removed.
*
* @return
*/
function rm_rf($dir)
{
if (!is_dir($dir)) {
return;
}
$filenames = scandir($dir);
foreach ($filenames as $filename) {
if ($filename === '.' || $filename === '..') {
continue;
}
$file = $dir . DIRECTORY_SEPARATOR . $filename;
if (is_file($file)) {
unlink($file);
} elseif (is_dir($file)) {
rm_rf($file);
}
}
// remove all empty folders, once all files are deleted
rmdir($dir);
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment