How to use php to force download multiple files in a zip archive

833 views
asked May 8, 2012 in General by redBee (760 points)
hello
I want to use php to force download multiple files in a zip archive,but I'm not sure how can I do this? Does anyone here has a the code for it? If so please help
thanks

1 Answer

0 like 0 dislike
answered May 8, 2012 by expert (14,380 points)
PHP function to download mutiple files in a zip archive


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();

  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;
}

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.
...