Posted By

BenJD on 02/22/11


Tagged

FileSystem


Versions (?)

Delete a Directory


 / Published in: PHP
 

Recurively iterate through a folder and all of it's subdirectories, delting every file.

  1. class RemoveDirectory
  2. {
  3. public function delete($rootDir)//:Boolean
  4. {
  5. $result = true;
  6.  
  7. if( !$this->removeDir($rootDir) )
  8. $result = false;
  9. else
  10. {
  11. rmdir($rootDir) or $result = false;
  12. }
  13.  
  14. return $result;
  15. }
  16.  
  17. private function removeDir($dir)//:Boolean
  18. {
  19. $result = true;
  20.  
  21. $rootDir = opendir($dir);
  22.  
  23. if($rootDir)
  24. {
  25. while(false !== ($file = readdir($rootDir)))
  26. {
  27. if($file != "." && $file != "..")
  28. {
  29. chmod($dir.$file, 0777);
  30.  
  31. if(is_dir($dir.$file))
  32. {
  33.  
  34. chdir('.');
  35. $this->removeDir($dir.$file.'/');
  36. rmdir($dir.$file) or $result = false;
  37. }
  38.  
  39. else
  40. unlink($dir.$file) or $result = false;
  41. }
  42.  
  43. }
  44.  
  45. closedir($rootDir);
  46. }
  47. else
  48. $result = false;
  49.  
  50. return $result;
  51. }
  52. }

Report this snippet  

You need to login to post a comment.