How to create a zip archive using PHP
by Justin Silverton
The following is a library that allows you to generate zip file archives using php.
<?php
include("ziplib.php");
$zipfile = new Ziplib;
$zipfile->zl_add_file("This is a test file","path/to/file","g9");
//You can stream the ZIP file or write it in a file on your server
header("Content-type: application/zip");
header("Content-Disposition: attachment; filename=\"testfile.zip\"");
echo $zipfile->zl_pack("zip file comments");
?>
This script will dynamically create a zip archive using the files specified with zl_add_file and output it to the browser (the final zip file will be named: testfile.zip).
Options
zl_add_file allows you to specify the compression level of the file file that will be added to the archive.
- n (none)
- b (bzip)
- g (gzip)
Download
The php zip library can be downloaded Here
11 Comments so far
Leave a reply






[…] On the JSLabs blog today, there’s a (short) new tutorial showing an alternate method to creating a Zip archive in PHP (rather than with the zip extension). […]
The zip extension of PHP allows that too. It’s bundled with PHP since version 5.2.0
That’s pretty cool. Here’s a suggestion, though:
Add a version of zl_pack() which does not buffer its content. As demonstrated above, one must use echo $foo->zl_pack(), which means that zl_pack buffers all of the data. For a large zip file this could exceed the memory limits for a user on a shared server. By addeding a zl_pack() variant which does not buffer, you can avoid this potential problem.
Also, it’s unusual to use both a class AND have a name prefix on the functions. That is, free-standing functions (non-member functions) often have a prefix (e.g. zl_xxx()), but there is little need for a class’ members to have them. e.g. instead of $zl->zl_pack(), use $zl->pack().
:)
Stephan,
Thanks for the tips!
Works great.
Many thanks. This is just what I needed. Simple, elegant and just works. Love you.
hi, i am new to this, I am not so understand, if i can pack a few files(which is an existing file at the server) together using the zl_add_file?
hi,
I’m wondering, is there an exception list. A list that you can add extentions or file directory not to be added into the archive?
thanks
This works very well, thanks.
I did run into that problem Stephan pointed out, where the zip file was too big to handle. How can I make a version of zl_pack() that doesn’t buffer its content?
Eliminating the buffering is probably not a good idea. try increasing the buffer size.
- Shelon Padmore
how can i compress jpg or gif file in zip format using ziplib class