Delete All Files


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

This isn't my code, but just thought I would share, since it took me so long to find. This is a function to delete a folder, all sub-folders, and files in one clean move.

Just tell it what directory you want deleted, in relation to the page that this function is executed. Then set $empty = true if you want the folder just emptied, but not deleted. If you set $empty = false, or just simply leave it out, the given directory will be deleted, as well.


Copy this code and paste it in your HTML
  1. <?php
  2. function deleteAll($directory, $empty = false) {
  3. if(substr($directory,-1) == "/") {
  4. $directory = substr($directory,0,-1);
  5. }
  6.  
  7. if(!file_exists($directory) || !is_dir($directory)) {
  8. return false;
  9. } elseif(!is_readable($directory)) {
  10. return false;
  11. } else {
  12. $directoryHandle = opendir($directory);
  13.  
  14. while ($contents = readdir($directoryHandle)) {
  15. if($contents != '.' && $contents != '..') {
  16. $path = $directory . "/" . $contents;
  17.  
  18. if(is_dir($path)) {
  19. deleteAll($path);
  20. } else {
  21. unlink($path);
  22. }
  23. }
  24. }
  25.  
  26. closedir($directoryHandle);
  27.  
  28. if($empty == false) {
  29. if(!rmdir($directory)) {
  30. return false;
  31. }
  32. }
  33.  
  34. return true;
  35. }
  36. }
  37. ?>

URL: http://php.net/manual/en/function.rmdir.php

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.