Posted By

fackz on 02/13/09


Tagged

delete dir remove directory


Versions (?)

Who likes this?

3 people have marked this snippet as a favorite

xtheonex
fackz
BrianCoyDesign


How to remove a (non-empty) directory


 / Published in: PHP
 

Here’s a snippet that can help you to remove a non-empty directory from the server. It’s a recursive function that deletes the directory with its files, folders and sub-folders.

  1. 1. <?php
  2. 2. function delete_directory($dir)
  3. 3. {
  4. 4. if ($handle = opendir($dir))
  5. 5. {
  6. 6. $array = array();
  7. 7.
  8. 8. while (false !== ($file = readdir($handle))) {
  9. 9. if ($file != "." && $file != "..") {
  10. 10.
  11. 11. if(is_dir($dir.$file))
  12. 12. {
  13. 13. if(!@rmdir($dir.$file)) // Empty directory? Remove it
  14. 14. {
  15. 15. delete_directory($dir.$file.'/'); // Not empty? Delete the files inside it
  16. 16. }
  17. 17. }
  18. 18. else
  19. 19. {
  20. 20. @unlink($dir.$file);
  21. 21. }
  22. 22. }
  23. 23. }
  24. 24. closedir($handle);
  25. 25.
  26. 26. @rmdir($dir);
  27. 27. }
  28. 28.
  29. 29. }
  30. 30.
  31. 31. $dir = '/home/path/to/mysite.com/folder_to_delete/'; // IMPORTANT: with '/' at the end
  32. 32.
  33. 33. $remove_directory = delete_directory($dir);
  34. 34. ?>

Report this snippet  

You need to login to post a comment.