download multiple files as zip in php

Solutions on MaxInterview for download multiple files as zip in php by the best coders in the world

showing results for - "download multiple files as zip in php"
Oonagh
06 Nov 2018
1<?php
2
3/* create a compressed zip file */
4function createZipArchive($files = array(), $destination = '', $overwrite = false) {
5
6   if(file_exists($destination) && !$overwrite) { return false; }
7
8   $validFiles = array();
9   if(is_array($files)) {
10      foreach($files as $file) {
11         if(file_exists($file)) {
12            $validFiles[] = $file;
13         }
14      }
15   }
16
17   if(count($validFiles)) {
18      $zip = new ZipArchive();
19      if($zip->open($destination,$overwrite ? ZIPARCHIVE::OVERWRITE : ZIPARCHIVE::CREATE) == true) {
20         foreach($validFiles as $file) {
21            $zip->addFile($file,$file);
22         }
23         $zip->close();
24         return file_exists($destination);
25      }else{
26          return false;
27      }
28   }else{
29      return false;
30   }
31}
32
33$fileName = 'myzipfile.zip';
34$files = array('uploads/profile1.jpeg', 'uploads/profile2.jpeg');
35$result = createZipArchive($files, $fileName);
36
37header("Content-Disposition: attachment; filename=\"".$fileName."\"");
38header("Content-Length: ".filesize($fileName));
39readfile($fileName);
40
41?>
42