Download multiple files as a zip-file using php


Php Problem Overview

How can I download multiple files as a zip-file using php?

Php Solutions

Solution 1 - Php

You can use the ZipArchive class to create a ZIP file and stream it to the client. Something like:

$files = array('readme.txt', 'test.html', 'image.gif');
$zipname = '';
$zip = new ZipArchive;
$zip->open($zipname, ZipArchive::CREATE);
foreach ($files as $file) {

and to stream it:

header('Content-Type: application/zip');
header('Content-disposition: attachment; filename='.$zipname);
header('Content-Length: ' . filesize($zipname));

The second line forces the browser to present a download box to the user and prompts the name The third line is optional but certain (mainly older) browsers have issues in certain cases without the content size being specified.

Solution 2 - Php

This is a working example of making ZIPs in PHP:

$zip = new ZipArchive();
$zip_name = time().".zip"; // Zip name
$zip->open($zip_name,  ZipArchive::CREATE);
foreach ($files as $file) {
  echo $path = "uploadpdf/".$file;
  $zip->addFromString(basename($path),  file_get_contents($path));  
   echo"file does not exist";

Solution 3 - Php

Create a zip file, then download the file, by setting the header, read the zip contents and output the file.

Solution 4 - Php

You are ready to do with php zip lib, and can use zend zip lib too,

// create object
$zip = new ZipArchive();   

// open archive 
if ($zip->open('') !== TRUE) {
    die ("Could not open archive");

// get number of files in archive
$numFiles = $zip->numFiles;

// iterate over file list
// print details of each file
for ($x=0; $x<$numFiles; $x++) {
    $file = $zip->statIndex($x);
    printf("%s (%d bytes)", $file['name'], $file['size']);
    print "

// close archive

and there is also php pear lib for this


All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
Questionuser213559View Question on Stackoverflow
Solution 1 - PhpcletusView Answer on Stackoverflow
Solution 2 - PhpSun LoveView Answer on Stackoverflow
Solution 3 - PhpPriyank BoliaView Answer on Stackoverflow
Solution 4 - Phpdev.meghrajView Answer on Stackoverflow