Empty directory recursively in PHP

Wednesday, August 24, 2011


Sometime we need to delete all contents in the directory whether it is any files or directory. At that time this function will be handy to fulfill our need. It empties the folder recursively, that means all the folders ans sub-folders are removed. 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'.
function emptyDirectory($dirname,$self_delete=false) {
   if (is_dir($dirname))
      $dir_handle = opendir($dirname);
   if (!$dir_handle)
      return false;
   while($file = readdir($dir_handle)) {
      if ($file != "." && $file != "..") {
         if (!is_dir($dirname."/".$file))
            @unlink($dirname."/".$file);
         else
            emptyDirectory($dirname.'/'.$file,true);
      }
   }
   closedir($dir_handle);
   if ($self_delete){
        @rmdir($dirname);
   }
   return true;
}

0 comments:

Post a Comment

 
back to top