I provided a simple function a few days ago that would unzip a file using PHP. As is usually always the case, it was followed up by a few emails asking for the best method of zipping a file or files. As it turns out, I’ve worked through some ZIP classes over the last few days in an attempt to identify with the best means of accomplishing a similar task for an online roster suite I’m writing. In my case, I needed to zip an iCal, PDF and a few other files that I could email to a user and deliver via a forced download.
Of course, as always, there’s no better reference than the PHP manual where you’ll literally find hundreds of examples.
The PHP function
This function will zip all the file contents referenced from within an array. The code was originally written by a friend of mine, Paul Tibbles, so he could zip up progress pictures on the fly requested by customers at his wire works factory.
<?php
function zipDownload($file_names,$archive_file_name,$file_path)
{
// Create object
$zip = new ZipArchive();
// Create file or error if unsuccessful
if ($zip->open($archive_file_name, ZIPARCHIVE::CREATE )!==TRUE) {
exit("cannot open <$archive_file_name>\n");
}
// Add each file $file_name array to archive
foreach($file_names as $files) {
$zip->addFile($file_path.$files,$files);
}
$zip->close();
// Send headers to force download
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=$archive_file_name");
header("Pragma: no-cache");
header("Expires: 0");
readfile("$archive_file_name");
// Comment out this line if you don't want to delete file after download
@unlink("$archive_file_name");
exit;
}
// We use time() as a 'unique' file name. For multiple users, something like *md5($username)-$time.zip* is usually good enough.
$time = time();
$file_names = array('image.jpg','document.doc','file.pdf');
$archive_file_name = "$time.zip";
$file_path = "/path/to/the/working/directory/";
zipDownload($file_names,$archive_file_name,$file_path);
?>
The function can easily be modified.
The directory you’re writing to should have appropriate write privileges.
Zip Classes
Over at PHPClasses.org, there are literally hundreds of excellent classes written under the GPL that can be very easily implemented into your projects. Of course, there are at least a dozen classes that relate to ZIP file usage that I’d recommend.
I regularly use a ZIP class written by Er. Rochak Chauhan simply because it’s easy to use and modify. A gentleman by the name of A. Grandt has written another class based upon Chauhan’s code which offers a little more functionality. Both classes come with full documentation and out-of-the-box examples.
|
|
If you liked this article, you may also like:


Recent Comments