Skip to content

Instantly share code, notes, and snippets.

@coreyhaines
Forked from AmyStephen/LocalWriteTest.php
Last active December 11, 2015 23:38
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 1 You must be signed in to fork a gist
  • Save coreyhaines/4677586 to your computer and use it in GitHub Desktop.
Save coreyhaines/4677586 to your computer and use it in GitHub Desktop.
<?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(0 => $this->path);
$files = array();
/** Recursive process of Folders. Discovery step for files and directories */
foreach ($objects as $name => $object) {
if (is_file($name)) {
$files[] = $name;
} elseif (is_dir($name)) {
$directories[] = $name;
}
}
foreach ($files as $file) {
unlink($file);
}
/** Sort folders in reverse order and delete one at a time */
arsort($directories);
foreach ($directories as $directory) {
rmdir($directory);
}
}
?>
@AmyStephen
Copy link

So. Very. Pretty. Thank you, kind sir! Loved those notes -- totally agree, very thoughtful, makes perfect sense.

It definitely is much more clear and even re-usable this way. Makes sense to split discover from action.

Not too shabby for "not knowing PHP." Guess it's all that smart Rubyiness.

@coreyhaines
Copy link
Author

:) Thanks. I've written in my fair share of languages, so php's syntax just looks like a mashup of several. :)

I'd prefer an actual recursive call, but I'm not sure how to do functions in php (or whether recursion is frowned upon in php).

@AmyStephen
Copy link

Yea, that'd be neat. That's a basic method for a class -- a function.

That array initialization to $this->path is interesting. Have not seen that before, going to have to play with that..

@AmyStephen
Copy link

I see, that's the seeded array entry for the initial directory -- you did that to remove the extra rmdir. Makes sense.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment