Last active
June 15, 2018 20:05
-
-
Save AmyStephen/4677117 to your computer and use it in GitHub Desktop.
Delete all files and folders in a 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 | |
$this->path = BASE_FOLDER . '/x/y/z'; | |
if (file_exists($this->path)) { | |
$objects = new RecursiveIteratorIterator ( | |
new RecursiveDirectoryIterator($this->path), | |
RecursiveIteratorIterator::SELF_FIRST); | |
$directories = array(); | |
$i = 0; | |
/** Recursive process of Folders */ | |
foreach ($objects as $name => $object) { | |
/** Remove files as found */ | |
if (is_file($name)) { | |
unlink($name); | |
/** Hold folders until end */ | |
} elseif (is_dir($name)) { | |
$directories[$i++] = $name; | |
} | |
} | |
/** Sort folders in reverse order and delete one at a time */ | |
arsort($directories); | |
foreach ($directories as $name) { | |
rmdir($name); | |
} | |
/** Remove the seed path folder */ | |
rmdir($this->path); | |
} | |
?> |
If I wrote this, also, I'd probably do a loop gathering up the files and directories into 2 lists, then loop over them to do the action.
I'm not a huge fan of mixing the discovery with the action, especially since the discovery phase (looping over $objects) has 2 possible outcomes: deleting a file or adding a directory to a list. By mixing the "discovery" and "action" phases, the code becomes a bit more difficult to change. For example, if you find a better way to do the recursive looping, you might have a harder time extracting it out. So, I'd probably do
foreach ($objects as $name => $object) {
if (is_file($name)) {
$files[] = $name;
} elseif (is_dir($name)) {
$directories[] = $name;
}
}
/** now loop over $files and unlink them **/
/** followed by looping over $directories and rmdir them **/
There we go. Got github to let me fork it. Here are my thoughts in the actual script:
https://gist.github.com/4677586
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Also, apparently (I've not written much php at all), arrays can be added to as
$directories[] = $name
which will add $name at the next highest index. So, if you initialize the array as
$directories = array(0 => $this->path)
then the added arrays found during the looping will just add at numerical index 1, 2, 3, 4, etc.
This eliminates the need for the $i index variable (never fun to have one of those floating around)