Tuesday, May 11, 2010

12:57 AM

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)

  //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");

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


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.


Alex said...

I have seen a lot of tools for work with zip files. But one of them saved me - fix corrupt zip once. It restored many my corrupted zip archives within short time and without even trying. Besides I recommended it some of my friends.

Ghprod said...

Hi, its works :D

i use it at

Duniakomik Downloader

Thanks alot .. btw how to check if ZipArchive was installed on our server?


Alexis said...

Zip archives very popular in the computer world. Like issue is very complicated and I think the next tool from one soft blog would be perfectly helpful here - either multiple or corrupt zip file.