zip and force download the files

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

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

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

Advertisements

2 Comments

  1. Kieran W said,

    June 28, 2009 at 7:31 pm

    Awesome ZIP tutorial! Have been looking for this for ages, I love how straight forward your tutorials are, no fluff or filler, great job, please post more!

    • rafeekphp said,

      June 29, 2009 at 5:45 am

      HI Kieran,

      Thanks.

      Rafeek 🙂


Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: