Last active
April 19, 2022 22:41
-
-
Save tsprates/4f1e821a85e197477cf082b624c34e2c to your computer and use it in GitHub Desktop.
Remove all files and subdirectories from a specific directory.
This file contains hidden or 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 | |
/** | |
* 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