Creating ZIP and TAR archives on the fly with PHP(Page 1 out of 5)
In this tutorial you will learn how to create ZIP and TAR archives dynamically using PHP and the PEAR::Archive_Zip and PEAR::Archive_Tar packages.
The easiest way to offer files for downloading on your website is to simply create the necessary archives (using WinZip or another program) on your own computer, and uploading the archives. But in some cases this isn't enough, for instance when you want to generate a unique archive for each person who downloads the archive. This means you'll have to create ZIP and TAR archives on the fly with PHP.
In this tutorial I will show you exactly how to do that. Thankfully there are two excellent libraries in the PHP Extension and Application Repository (PEAR) which makes it a lot easier since all the hard stuff has been written for us already.
You will also learn how to stream these dynamically created archives using the right headers so that the browser will know it's an archive, and not a normal PHP page.
Let's start with the most important: creating the archives.
Creating the archives
To create the archives we'll be using the PEAR::Archive_Zip package and the PEAR::Archive_Tar package. Since they're PEAR packages, you'll also have to download the main PEAR.php file. Either you can download and install the full PEAR library, or you can download the PEAR.php file by clicking here. Since you don't need anything except the PEAR.php file I recommend downloading it from the link I just gave you, instead of installing the full PEAR library.
Let's start of with the PEAR::Archive_Zip package. It's surprisingly easy to use, and it only takes three lines to create a new zip file:
// Create instance of Archive_Zip class, and pass the name of our zipfile
$zipfile = New Archive_Zip('myzipfile.zip');
// Create a list of files and directories
$list = array('example.txt');
// Create the zip file
echo 'Zip file created';
Let's go through this example. First we include the PEAR::Archive_Zip package, after which we create an instance of the Archive_Zip class and pass the name of the zipfile we are going to create as the first parameter.
Then we build a list of all the files and directories that should be included in the zipfile. In the example we include only one file called example.txt which is located in the same directory as the script. This list of files is passed to the create() method of the object, and the actual zip file is created, and will be located in the same path as your script.
All seems very simple, but there are a few catches. For one, if the path isn't writable it won't be possible to create the zip file, and in many cases, the script path isn't writable, so we'll have to think of a solution.