PHP - How to create zip file and download multiple files using ZipArchive ?

PHP - How to create zip file and download multiple files using ZipArchive ?

In this PHP Tutorial, I am going to tell you how to create zip file using PHP's ZIP class "ZipArchive".

You can use this example to download multiple files at the same time by creating zip file, you can simply add the downloading files in a zip with the help of PHP's ZIP class.

In this example, I will use open() method to open or create any zip file and addFile() method is used to add files to archive from the given path and close() method is used to close zip file safely.

Example:
<?php

/* create a compressed zip file */
function createZipArchive($files = array(), $destination = '', $overwrite = false) {

   if(file_exists($destination) && !$overwrite) { return false; }

   $validFiles = array();
   if(is_array($files)) {
      foreach($files as $file) {
         if(file_exists($file)) {
            $validFiles[] = $file;
         }
      }
   }

   if(count($validFiles)) {
      $zip = new ZipArchive();
      if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) == true) {
         foreach($validFiles as $file) {
            $zip->addFile($file,$file);
         }
         $zip->close();
         return file_exists($destination);
      }else{
          return false;
      }
   }else{
      return false;
   }
}

$fileName = 'myzipfile.zip';
$files = array('uploads/profile1.jpeg', 'uploads/profile2.jpeg');
$result = createZipArchive($files, $fileName);

header("Content-Disposition: attachment; filename=\"".$fileName."\"");
header("Content-Length: ".filesize($fileName));
readfile($fileName);

?>

You have to set header correctly to force download. You can pass the array of files in createZipArchive() function.

Phone: (+91) 8800417876
Noida, 201301
Betwinner
pendik escort
kartal escort