Empty directory recursively in PHP


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

This function empties the folder recursively. Two parameters are passed in the function, First one is the directory to be emptied and second one is the flag to determine whether to delete the given folder. If set 'true', given folder is also removed at last. If emptying is our need then you should pass 'false'.


Copy this code and paste it in your HTML
  1. function emptyDirectory($dirname,$self_delete=false) {
  2. if (is_dir($dirname))
  3. $dir_handle = opendir($dirname);
  4. if (!$dir_handle)
  5. return false;
  6. while($file = readdir($dir_handle)) {
  7. if ($file != "." && $file != "..") {
  8. if (!is_dir($dirname."/".$file))
  9. @unlink($dirname."/".$file);
  10. else
  11. emptyDirectory($dirname.'/'.$file,true);
  12. }
  13. }
  14. closedir($dir_handle);
  15. if ($self_delete){
  16. @rmdir($dirname);
  17. }
  18. return true;
  19. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.