Clean Out A Folder - Remove A Folders Complete Contents


/ Published in: PHP
Save to your folder(s)

This is a simple function that will take a folder path and remove all of its contents including files and directories.


Copy this code and paste it in your HTML
  1. <?php
  2.  
  3. function emptyDir($path) {
  4.  
  5. // INITIALIZE THE DEBUG STRING
  6. $debugStr = '';
  7. $debugStr .= "Deleting Contents Of: $path<br /><br />";
  8.  
  9. // PARSE THE FOLDER
  10. if ($handle = opendir($path)) {
  11.  
  12. while (false !== ($file = readdir($handle))) {
  13.  
  14. if ($file != "." && $file != "..") {
  15.  
  16. // IF IT"S A FILE THEN DELETE IT
  17. if(is_file($path."/".$file)) {
  18.  
  19. if(unlink($path."/".$file)) {
  20. $debugStr .= "Deleted File: ".$file."<br />";
  21. }
  22.  
  23. } else {
  24.  
  25. // IT IS A DIRECTORY
  26. // CRAWL THROUGH THE DIRECTORY AND DELETE IT'S CONTENTS
  27.  
  28. if($handle2 = opendir($path."/".$file)) {
  29.  
  30. while (false !== ($file2 = readdir($handle2))) {
  31.  
  32. if ($file2 != "." && $file2 != "..") {
  33. if(unlink($path."/".$file."/".$file2)) {
  34. $debugStr .= "Deleted File: $file/$file2<br />";
  35. }
  36. }
  37.  
  38. }
  39.  
  40. }
  41.  
  42. if(rmdir($path."/".$file)) {
  43. $debugStr .= "Directory: ".$file."<br />";
  44. }
  45.  
  46. }
  47.  
  48. }
  49.  
  50. }
  51.  
  52. }
  53. return $debugStr;
  54. }
  55.  
  56. ?>

URL: http://www.aristoworks.com

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.