Skip to content

Instantly share code, notes, and snippets.

@AmyStephen
Last active June 15, 2018 20:05
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 2 You must be signed in to fork a gist
  • Save AmyStephen/4677117 to your computer and use it in GitHub Desktop.
Save AmyStephen/4677117 to your computer and use it in GitHub Desktop.
Delete all files and folders in a directory
<?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);
}
?>
@coreyhaines
Copy link

Would it make sense to initialize $directories with $this -> path, so the directory removal loop will remove it. This will eliminate the need to have a separate, final rmdir

@coreyhaines
Copy link

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)

@coreyhaines
Copy link

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 **/

@coreyhaines
Copy link

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