How to create zip file archives in PHP and serve for download

April 26th, 2010No Comments

Creating dynamically zip file archives in PHP is very easy. I wanted to give an option in a client site after uploading files, they can download all the uploaded files. Instead of giving an option to download one by one, i was looking for an option to create zip file and give an option to download.

For this if you have installed PhpMyadmin, under libraries folder, you can see two files. These two php class files you can use to create and unzip archive files easily.

1. zip.lib.php
2. unzip.lib.php

Example :


require_once '/library/zip.lib.php';
require_once '/library/unzip.lib.php';
$zip = new zipfile();
$filename = 'test-image.png'; // path of the file.
$fsize = @filesize($filename); // file size
$fh = fopen($filename, 'rb', false);
$data = fread($fh, $fsize);
$zip->addFile($data,$filename);
$zippedfile = $zip->file();
header("Content-Description: File Transfer");
header("Content-Disposition: attachment; filename=TestArchive.zip");
header("Content-Type: application/zip");
header("Content-length: " . strlen($zippedfile) . "\n\n");
header("Content-Transfer-Encoding: binary");
// output data to the browser
echo $zippedfile;

If you don’t want to include the folder structure in a zip file, just execute above php function under the same directory, from where you want to archive files.

References :
1. Create ZIP file archives and serve for download
2. http://davidwalsh.name/create-zip-php
3. PclZip
4. PHP ZipArchive class

Related Posts:

Tagged :

Comments are closed.