deletetree.php 1.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354
  1. <?php
  2. /*
  3. * StatusNet - the distributed open-source microblogging tool
  4. * Copyright (C) 2008, 2009, StatusNet, Inc.
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the GNU Affero General Public License as published by
  8. * the Free Software Foundation, either version 3 of the License, or
  9. * (at your option) any later version.
  10. *
  11. * This program is distributed in the hope that it will be useful,
  12. * but WITHOUT ANY WARRANTY; without even the implied warranty of
  13. * MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the
  14. * GNU Affero General Public License for more details.
  15. *
  16. * You should have received a copy of the GNU Affero General Public License
  17. * along with this program. If not, see <http://www.gnu.org/licenses/>.
  18. */
  19. /**
  20. * Recursively deletes a directory tree.
  21. *
  22. * @param string $folder The directory path.
  23. * @param bool $keepRootFolder Whether to keep the top-level folder.
  24. * @return bool TRUE on success, otherwise FALSE.
  25. */
  26. function deleteTree(
  27. $folder,
  28. $keepRootFolder = false
  29. ) {
  30. // Handle bad arguments.
  31. if (empty($folder) || !file_exists($folder)) {
  32. return true; // No such file/folder exists.
  33. } elseif (is_file($folder) || is_link($folder)) {
  34. return @unlink($folder); // Delete file/link.
  35. }
  36. // Delete all children.
  37. $files = new RecursiveIteratorIterator(
  38. new RecursiveDirectoryIterator($folder, RecursiveDirectoryIterator::SKIP_DOTS),
  39. RecursiveIteratorIterator::CHILD_FIRST
  40. );
  41. foreach ($files as $fileinfo) {
  42. $action = ($fileinfo->isDir() ? 'rmdir' : 'unlink');
  43. if (!@$action($fileinfo->getRealPath())) {
  44. return false; // Abort due to the failure.
  45. }
  46. }
  47. // Delete the root folder itself?
  48. return (!$keepRootFolder ? @rmdir($folder) : true);
  49. }