Force download multiple files in a zip archive using PHP
- Tuesday, September 2, 2008, 16:44
- how-to, php, tips and technique
- 36 comments
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;
}
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.
Popularity: 10% [?]
Related Posts
» Prevent Directory Listing using .htaccess
» Uploading large(big) files in PHP using .htaccess
» Absolute path and Relative path file inclusion in PHP
» Blogger Sucks, Wordpress Wowww!!

Usefull!!
tks Roshan to share this code.
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
@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….
Very useful for community sites, useful with a checkox list, just gotta know how to intergrate it =P
Thanks again
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.
Christoph……thanks for the the idea…I’ve already thought for that and you’ll be getting that post soon…
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?
@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
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
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();
}
@KevinK- Why don’t you pass the headers as I’ve posted above, it is working fine…
hey, thanks for sharing ….
very nice script, im using it
Thanks. The script saved me some time.
Excellent script … thanks for the script man ..
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
@bharat- to simplify this you can use opendir() and array_push() function to add these files to array……
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.
@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….
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.
nice script. i wonder i you have the deletion script as well. cron job running script.
could this work with files that are stored in a database as blobs?
@Luke – I never store the files in database as a blob as it increases the database overhead….so haven’t tested with blob data…
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
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
thanks a ton
you code saved my time
…..
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?
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
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!
I tried the code given by but I m getting error:The compressed (zipped) folder is invalid or corrupted..plz help me out
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.
How can i get this to download all files of a certain file-type in a certain directory?
thanks for any help.
hi! can u help me? i was trying to download a multiple files. does it take many
to do that? thanks
van
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
Respected Sir
I have compress the zip file then this errot is occure
No file to extrect erro
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.
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