When developing web applications, it is very common that you will encounter to deal with a list of different file formats. I have been doing web development for about one and half years, the file formats that I have encountered are pure TXT file, CSV, XML, INI, and different types of image file formats, like GIF, PNG and JPG. The common tasks to deal with those file formats are basically reading and writing to them. Since they are so common for day to day web development, it is not surprised that PHP comes with a wide variety of both built-in functions and external libraries to connect to, and work with, almost any file format you can name.
I haven’t encountered this situation before, but let’s think about one scenario. You need to write a script to transfer a large amount of files your script created to a remote server. It is simple, right? All you need to do is to create a SSH key to allow script to remotely login to the server and upload the files one by one. But the problem is that you are dealing with large amout of files, and it is not efficient to copy file one by one. The ideal solution is to zip all the files into one zip file, transfer it across to the server, and unzip from the server. Can PHP create a zip file for you? Luckily we have PEAR library available, and it can just do the job for us in a few lines of code.
Here is what you need to do.
[li]Download the PEAR base system from here
[li]Download the PEAR Archive_Zip package from here
Unzip the files to the appropriate location, and change your php include_path accordingly. Now you are ready to start the action.
Creating ZIP archives
This is your script needs to do, get a list of file names, and create a zip file.
create( $filesList ) )
[tab]echo "Zip file created successfully!";
[tab]echo "Unable to create zip file";
Now once you have copied the zip file created across to the server machine, you can create a separate script to unzip the file.
foreach ( $filesList as $file )
[tab]foreach ( $file as $key => $value )
[tab][tab]echo "$key: $value
The output of listContent() is a structured array of arrays, with each array element representing an individual file from the archive. Typically, each element holds information on the name of the corresponding file, its index position, its status, its size (both compressed and uncompressed) and its time of last modification. It’s fairly easy to extract this information with a loop and re-format it to make it more presentable.
As the examples above illustrate, PEAR’s Archive_Zip class is quite versatile and allows you to perform some fairly complex ZIP file interaction with just a few lines of code. Hopefully, the sample scripts above sparked some ideas about how you can use this class in your daily development activities and got you interested in experimenting with it. Have fun!