Posted By

nilambar on 02/14/11


Tagged

php empty directory


Versions (?)

Who likes this?

2 people have marked this snippet as a favorite

Jarek
surekin


Empty directory recursively in PHP


 / Published in: PHP
 

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'.

  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  

You need to login to post a comment.