Force download multiple files in a zip archive using PHP

Advertisement

In this post, I’ll show you how can you download the multiples files in a zip archive using PHP. I’ve made a function in PHP where you’ve to pass the parameters the array of files to be zipped, the second parameter is file name as which zip archive file has to be downloaded and finally the path of files where files to be zipped are located.(assuming that they are all in same folder)

PHP function to download mutiple files in a zip archive

//function to zip and force download the files using PHP
function zipFilesAndDownload($file_names,$archive_file_name,$file_path)
{
  //create the object
  $zip = new ZipArchive();
  //create the file and throw the error if unsuccessful
  if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
    exit("cannot open <$archive_file_name>\n");
  }

  //add each files of $file_name array to archive
  foreach($file_names as $files)
  {
    $zip->addFile($file_path.$files,$files);
  }
  $zip->close();

  //then send the headers to foce download the zip file
  header("Content-type: application/zip");
  header("Content-Disposition: attachment; filename=$archive_file_name");
  header("Pragma: no-cache");
  header("Expires: 0");
  readfile("$archive_file_name");
  exit;
}

Download Source code

In the above PHP function, first of all the object of ZipArchive class. Remember that this library is bundled in PHP after the version of PHP 5.2 only.If you’re using the PHP version older than that one then you’ve to get it from PECL extension.

After that, we’ve tried to create the zip arhive with the open() function using the ZIPARCHIVE::CREATE flag.After successfully creating the archive, each files whose names are passed as array are added to zip file using addFile() function of ZipArchive() class.Then, this zip archive is closed using close() function of same class.

And, finally different headers are passed through PHP to force download the newly created zip file.

Example of Using Above PHP function

  $file_names=array('test.php','test1.txt');
  $archive_file_name='zipped.zip';
  $file_path=dirname(__FILE__).'/';
  zipFilesAndDownload($file_names,$archive_file_name,$file_path);

The above PHP function call is straighforward and after calling that function you’ll get the zip archive containing mutiple files passed as array in the first parameter of the function.

Tags: ,

Enter your email address and get free tutorials, tips and tricks of PHP, Ajax, JavaScript and CSS directly delivered to you email inbox:

48 Comments on “Force download multiple files in a zip archive using PHP”

  • Felix wrote on 2 September, 2008, 17:43

    Usefull!!
    tks Roshan to share this code.

  • SNaRe wrote on 2 September, 2008, 17:54

    Firstly thank you for share. But I have a question. I wrote a smilar script for myself.
    It’s also using readfile function.
    I’m using external links to download . They are not on my host.
    So when i want use readfile functions will it use my websites bandwith (because of readfile) or will it use from external website.
    I hope i could explain

  • Roshan wrote on 3 September, 2008, 6:01

    @SNaRe – You can see the description from php.net
    Reads a file and writes it to the output buffer.

    Which clearly tells that it reads the file from external source and write it to the output butter which is gonna consume the bandwidth of both websites….

  • Tarquin wrote on 4 September, 2008, 6:40

    Very useful for community sites, useful with a checkox list, just gotta know how to intergrate it =P

    Thanks again :)

  • Christoph wrote on 6 September, 2008, 6:19

    Great,thx for sharing! Would be great with a post doing the reversal thing, extracting files from an uploaded zip-file. Challenge, Roshan ;)

    Best regards, pal!

    C.

  • Roshan wrote on 6 September, 2008, 15:50

    Christoph……thanks for the the idea…I’ve already thought for that and you’ll be getting that post soon…

  • KevinK wrote on 7 September, 2008, 3:40

    The example creates a .zip on the server which can be opened. But the downloaded file is a slightly different size and Winzip says it is corrupt. Is there some additional header magic?

  • Roshan wrote on 7 September, 2008, 4:33

    @kevinK- I had the same problem of corrupted archive. It is the but of the zip library upgrade your PHP version to latest or upgrade the library file from CVS.

    http://bugs.php.net/bug.php?id=39506

  • Muhammad Ali wrote on 10 September, 2008, 9:14

    Oh thats nice, i was in search of such a code that can generate dynamically the .zip file, i got it here, thanks for sharing

  • KevinK wrote on 10 September, 2008, 14:51

    Again, the zip created on the server is OK. It can be opened. It is after downloading to the client that the zip can’t be opened.

    The server and client versions are the same size. What could be wrong with this code?

    function download_zip($filename) {
    ini_set(“zlib.output_compression”, “Off”);
    header(“Cache-Control: must-revalidate, post-check=0, pre-check=0″);
    header(“Cache-Control: private”);
    header(‘Pragma: no-cache’);
    header(‘Expires: 0′);
    header(“Content-Description: File Transfer”);
    header(‘Content-disposition: attachment; filename=’.basename($filename));
    header(“Content-Type: application/zip”);
    header(“Accept-Ranges:bytes”);
    header(“Content-Length:”.filesize($filename));
    $fp = @fopen($filename,”rb”);
    fpassthru($fp);
    fclose($fp);

    ob_flush();
    flush();
    }

  • Roshan wrote on 10 September, 2008, 15:23

    @KevinK- Why don’t you pass the headers as I’ve posted above, it is working fine…

  • diego wrote on 11 September, 2008, 3:53

    hey, thanks for sharing ….
    very nice script, im using it

  • W. H. Evans wrote on 12 September, 2008, 11:30

    Thanks. The script saved me some time.

  • danish wrote on 26 September, 2008, 10:28

    Excellent script … thanks for the script man ..

  • bharat wrote on 3 October, 2008, 13:38

    Hi, roshan

    I have a large number of files (about 2000 html files) which is inside a folder and i want to download it by using this function , is it possible?

    but i think that creating an array for all these 2000 html files for first argument of these function is hard work.

    can you provide some solution

  • Roshan wrote on 3 October, 2008, 15:24

    @bharat- to simplify this you can use opendir() and array_push() function to add these files to array……

  • Pranjal wrote on 10 November, 2008, 21:51

    Is there a way to create a form that has check boxes for downloading files. By this I mean, if I want to download file 1, 2, 5, and 7, I can check the 1,2,5, and 7 checkboxes, hit submit, and they would all download to my computer in a zip format from a remote or local server.

  • Roshan wrote on 11 November, 2008, 10:09

    @pranjal – you can do it by using the checkbox and use array_push() function to store the file name in the array when posted…….simple….

  • pranjal wrote on 11 November, 2008, 23:21

    Thanks, for the reply Roshan.Checkboxes are working.Now I am having one more problem. The script creates a zip folder also on the server for each download. Is there a way that I can differentiate between the two zip files. one which the user is downloading and other which is getting saved on the server. So that I can put the server zip file in a different folder.

  • maleos wrote on 4 December, 2008, 8:54

    nice script. i wonder i you have the deletion script as well. cron job running script.

  • Luke wrote on 19 December, 2008, 15:20

    could this work with files that are stored in a database as blobs?

  • Roshan wrote on 20 December, 2008, 15:04

    @Luke – I never store the files in database as a blob as it increases the database overhead….so haven’t tested with blob data…

  • Smitha wrote on 30 December, 2008, 23:48

    I would like to use this function to download zip files, but I am using PHP 5.2. Could you please let me know how to get the ZipArchive class from PECL extension.
    Thanks,
    Smitha

  • Muhammad Adnan wrote on 24 March, 2009, 19:56

    nice sharing ,
    i have problem regarding the zip files , please see my question here
    http://www.sitepoint.com/forums/showthread.php?p=4198615&posted=1#post4198615
    thanks

  • raman wrote on 3 June, 2009, 12:54

    thanks a ton

    you code saved my time
    …..

  • Jeff wrote on 5 June, 2009, 22:31

    If anybody is still responding to this area, I would greatly appreciate suggestions for the best way to do this in an update and download situation for multiple users. The scenario is that I have a single template .zip archive file that I would like to read into memory, update with changes (virtually), and download as a .zip for any one user’s particular request. Multiple users would be doing this at the same time with different updates. I cannot have .zips piling up in the file system, and I cannot change and save copies of the original template .zip for each operation. Any ideas of how to safely do this?

  • Rajesh wrote on 8 June, 2009, 12:24

    Roshan , I used your code but its not downloading the files which i have specified in array variable. When i load my page , its asking me to download the file and when i do and open the file its showing ,the file has not downloaded properly . I am using version of Php 5.2 , please help me out

  • Vee wrote on 18 August, 2009, 20:44

    Great script! I’m trying to retrieve files that are not in the same directory as the script. I tried adding an additional file_path, but I cannot get it to work.

    Any Ideas?

    Thanks!

  • Manoj Kumar wrote on 9 September, 2009, 5:02

    I tried the code given by but I m getting error:The compressed (zipped) folder is invalid or corrupted..plz help me out

  • calvinlyp wrote on 14 September, 2009, 14:56

    wonderful piece of work done!
    great job!

    i got it working however it print quite a lot of unnecessary ascii code with the file names on to the website .
    is there a way t remove the display of the text?

    any help will be greatly appreciated.

  • P wrote on 7 October, 2009, 22:49

    How can i get this to download all files of a certain file-type in a certain directory?
    thanks for any help.

  • evan wrote on 3 November, 2009, 7:57

    hi! can u help me? i was trying to download a multiple files. does it take many

    to do that? thanks

    van

  • evan wrote on 3 November, 2009, 7:59

    hi! can u help me? i was trying to download a multiple files. does it take many

    header(‘Content-type: application/pdf’);
    header(‘Content-Disposition: attachment; filename=”C:\upload\ATV_Form.pdf”‘);
    readfile(‘test.pdf’);

    to do that? thanks

    van

  • virendra wrote on 10 December, 2009, 11:11

    Respected Sir
    I have compress the zip file then this errot is occure
    No file to extrect erro

  • rockface wrote on 4 January, 2010, 20:34

    TIPS….
    1. Make sure “<?php” is on the very first line and “?>” is on the very last line…
    The CR/LF will show up in your zip file and it will be corrupted!

    2. If you have any errors in your php code the resulting zip file will actually be a text file containing your error message. Save it to you desktop and rename it to zip.txt to view the error.

  • deepthi wrote on 7 January, 2010, 8:26

    Hai Roshan,

    I am using s3 object to upload files, so files will sit on different server other than website server. I am trying to download a file of more than 10Mb

    I have used the headers which you have mentioned above.

    But instead of using readfile i am using $s3->getObject(); and then var_dump() to output the result.

    My problem is the file is not downloading, 0 bytes are downloaded.

    Does it require any extra headers as its a big file.

    Thanks,
    Deepthi

  • alessio wrote on 11 March, 2010, 15:12

    I get PHP error…
    readfile(my-file.zip) [function.readfile]: failed to open stream: No such file or directory

    How to fix this?

  • Rajiv Bawa wrote on 25 March, 2010, 12:59

    Hi:
    Please solve my problem.
    I am getting:
    error: Class ‘ZipArchive’ not found in download.php on line 11
    Rajiv Bawa

  • Rajiv Bawa wrote on 25 March, 2010, 13:00

    Hi:
    Please solve my problem.
    I am getting.
    Fatal error: Class ‘ZipArchive’ not found in download.php on line 11
    Rajiv Bawa

  • santosh wrote on 1 April, 2010, 6:06

    i am using your code but by default only 1kb zip folder is create.
    the zip folder is empty there is no file in that zip folder.

    Please solve my problem.

  • Jurgen wrote on 27 April, 2010, 12:06

    The code works very fine. I still have one problem. I want another page to load when the download is started. But every code i put after the line thats starts the script is not excecuted.
    Thanks

    Jurgen

  • Timothy Leung wrote on 1 June, 2010, 8:00

    Thx for providing this great example.

    The script works great.

    However, when i tried to use

    $file_path=dirname(__FILE__).’/files/';
    instead of
    $file_path=dirname(__FILE__).’/';

    the zip file corrupted as a result.

    please advise.

  • antara wrote on 13 August, 2010, 10:36

    Your code is too good. But i can’t get what i have to do exactly to get rid of corrupted zip. please tell me in details.

  • Andy wrote on 9 February, 2011, 6:44

    Thanks for this. Why can’t all useful solutions be demonstrated as simply as this!

  • MicroWise wrote on 18 February, 2011, 20:36

    this worked well for me! Thank you so much for this. i was lookin for a way to hide file URLs from users, this does it perfectly well :)

    just one tiny question, if i triggered this script on a click of a form button, is there anyway to download the file WITHOUT having to open a new window/tab?

    currently i have this line in the function that is called on clicking the button:
    window.open(‘dl_files.php?attId=’+attId);

  • Nida ali wrote on 11 March, 2011, 10:12

    It is working fine on local server but when i upload it. it downloads all the files. But i have given some restriction on files. that it does not follow. it downloads all the files that finds on that folder.
    Do you have any solution?

  • Neethu wrote on 15 March, 2011, 12:02

    hi
    how to get ZipArchive class.pls answer.

  • Neethu wrote on 15 March, 2011, 12:05

    anybody know the code of ZipArchive() class.

Write a Comment

 


Copyright © 2014 Roshan Bhattarai's Blog. All rights reserved.
Powered by WordPress.org, Custom Theme and ComFi.com Calling Card Company.