1
0

recursive-remove-dir.php 2.2 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889
  1. <?php
  2. /**
  3. * dolphin. Collection of useful PHP skeletons.
  4. * Copyright (C) 2013 Johannes 'Banana' Keßler
  5. *
  6. * This program is free software: you can redistribute it and/or modify
  7. * it under the terms of the COMMON DEVELOPMENT AND DISTRIBUTION LICENSE
  8. *
  9. * You should have received a copy of the
  10. * COMMON DEVELOPMENT AND DISTRIBUTION LICENSE (CDDL) Version 1.0
  11. * along with this program. If not, see http://www.sun.com/cddl/cddl.html
  12. */
  13. /**
  14. * delete and/or empty a directory
  15. *
  16. * $empty = true => empty the directory but do not delete it
  17. *
  18. * @param string $directory
  19. * @param boolean $empty
  20. * @param int $fTime If not false remove files older then this value in sec.
  21. * @return boolean
  22. */
  23. function recursive_remove_directory($directory,$empty=false,$fTime=0) {
  24. // if the path has a slash at the end we remove it here
  25. if(substr($directory,-1) == '/') {
  26. $directory = substr($directory,0,-1);
  27. }
  28. if(!file_exists($directory) || !is_dir($directory)) {
  29. // we return false and exit the function
  30. return false;
  31. }
  32. elseif(!is_readable($directory)) {
  33. // return false and exit the function
  34. return false;
  35. }
  36. else {
  37. // we open the directory
  38. $handle = opendir($directory);
  39. // and scan through the items inside
  40. while (false !== ($item = readdir($handle))) {
  41. // if the filepointer is not the current directory
  42. // or the parent directory
  43. //if($item != '.' && $item != '..' && $item != '.svn') {
  44. if($item[0] != '.') {
  45. // we build the new path to delete
  46. $path = $directory.'/'.$item;
  47. // if the new path is a directory
  48. if(is_dir($path)) {
  49. // we call this function with the new path
  50. recursive_remove_directory($path);
  51. }
  52. else {
  53. // we remove the file
  54. if($fTime !== false && is_int($fTime)) {
  55. // check filemtime
  56. $ft = filemtime($path);
  57. $offset = time()-$fTime;
  58. if($ft <= $offset) {
  59. unlink($path);
  60. }
  61. }
  62. else {
  63. unlink($path);
  64. }
  65. }
  66. }
  67. }
  68. // close the directory
  69. closedir($handle);
  70. // if the option to empty is not set to true
  71. if($empty == false) {
  72. // try to delete the now empty directory
  73. if(!rmdir($directory)) {
  74. // return false if not possible
  75. return false;
  76. }
  77. }
  78. return true;
  79. }
  80. }
  81. ?>