When developing Web applications, you may encounter files in different formats-CSV data, password files, XML-encoded content, and binary data in different forms. Your PHP script will frequently interact with these files, read data from them, and write data into them. Because some files in these formats need to be processed, you should not be surprised that there are so many types of built-in functions and external libraries in PHP, used to connect and use almost all file formats that you can name.
This guide is about such a file format, which may be encountered by application developers almost every day: ZIP format. Generally, this format is used to transmit files through email and remote connection. It can compress multiple files into one file. Therefore, the hard disk space of files is reduced, and it is easier to move them. PHP can read and create these ZIP files through its ZZipLib plug-in and the Archive_Zip class of PEAR.
I will assume that you already have Apache running properly, installed PHP, And the PEAR Archive_Zip class has been correctly installed.
Note: You can directly install the PEAR Archive_Zip package from the Internet, download it, or use the provided instructions.
Create a ZIP file
Let's start with a simple example: Create a ZIP file that includes several other files dynamically. Start with the script in list.
List
- <?php
- include ('Archive/Zip.php'); // imports
-
- $obj = new Archive_Zip('test.zip'); // name of zip file
-
- $files = array('mystuff/ad.gif',
- 'mystuff/alcon.doc',
- 'mystuff/alcon.xls'); // files to store
-
- if ($obj->create($files)) {
- echo 'Created successfully!';
- } else {
- echo 'Error in file creation';
- }
- ?>
This script is very simple, but it is worth a closer look:
First, create an Archive_Zip class instance and initialize it with the path and name of the file to be created. In this example, the file is named test.zip and is located in the current directory.
Next, initialize an array to list the files to be compressed and store them together with their locations on the hard disk. These locations are listed in absolute or relative terms. However, A key consideration is that the script must have the read permission on the files or disk locations.
Finally, use the create () method to compress and merge the specified files to actually build the file. This method accepts the file list as input and returns a Boolean logical value indicating whether the file is successfully created. Note: It is very important that the script must have the write privilege in the directory where the file is created. Otherwise, the create () method will fail. This is a common error that causes most new users to fail.
Now, after modifying the source file list and target file location to reflect your local system configuration, try to run the above script. If it is convenient, archive_zipshould be able to find the file you listed and compress it to the file in the ZIP file named test.zip.
View the content of a ZIP file
So how can we see the content in the existing ZIP file? Archive_Zip lets allows you to achieve this through its listContent () method. The following is an example (List B ):
List B
- <?php
- include ('Archive/Zip.php'); // imports
-
- $obj = new Archive_Zip('test.zip'); // name of zip file
-
- $files = $obj->listContent(); // array of file information
-
- foreach ($files as $f) {
- foreach ($f as $k => $v) {
- echo "$k: $v\n";
- }
- echo "\n";
- }
- ?>
The output of listContent () is an array consisting of arrays. Each array element represents a separate file in the file. Generally, each element contains relevant information, such as the name of the corresponding file, its index location, status, size (after compression and before compression), and the last modification time. This information can be easily extracted using a loop, and its format can be reset as in column B for better transmission. The following is an example of the output (List C ):
List C
- filename: mystuff/alcon.xls
- stored_filename: mystuff/alcon.xls
- size: 113664
- compressed_size: 35902
- mtime: 1141996836
- comment:
- folder:
- index: 0
- status: ok
Add a new file to an existing ZIP file
An interesting feature of the Archive_Zip class is that it can add new files to existing files through the add () method. To illustrate this tutorial, let's go back to test.zip and try to add a new file to it (List D ):
List D
- <?php
- include ('Archive/Zip.php'); // imports
-
- if (file_exists('test.zip')) {
- $obj = new Archive_Zip('test.zip'); // name of zip file
- } else {
- die('File does not exist');
- }
-
- $files = array('otherstuff/montecarlo.png'); // additional files to store
-
- if ($obj->add($files)) {
- echo 'Added successfully!';
- } else {
- echo 'Error in file addition';
- }
- ?>
As you can see, adding a new file program to an existing file is very similar to creating a new file: initialize a new Archive_Zip object that points to the archive file represented by the question mark, create an array that represents the list of objects to be added, and then input the add () method to this array. Like the create () method, add () returns a Boolean signal to indicate whether the addition is successful. As before, one of the main problems is that you should not forget to have sufficient permissions: Make sure that the script has proper permissions to read the source file and write the compressed file back to the hard drive.
Delete an existing ZIP file
You can delete an object, just like adding a file. The Archive_Zip class has the delete () method, allowing you to remove files from existing files. List E illustrates this ..
List E
- <?php
- include ('Archive/Zip.php'); // imports
-
- if (file_exists('test.zip')) {
- $obj = new Archive_Zip('test.zip'); // name of zip file
- } else {
- die('File does not exist');
- }
-
- $files = array('mystuff/ad.gif', 'otherstuff/montecarlo.png'); // files to delete
-
- if ($obj->delete(array('by_name' => $files))) {
- echo 'Deleted successfully!';
- } else {
- echo 'Error in file deletion';
- }
- ?>
Here, an array of files to be deleted is created, and then the delete () method is entered. Note that the special parameter "by_name" in the delete () call indicates that Archive_Zip only deletes files that exactly match the file name. If the deletion is successful, the delete () method returns true.
In addition to selective deletion in this form, the delete () method also supports large-scale destruction of files that match a specific type or regular expression. Regular Expressions in Perl and PHP are supported by the "by_ereg" or "by_preg" parameter. List F is an example to illustrate how to use this method and delete all *. doc files in an archive file by using the regular expression of Perl.
List F
- <?php
- include ('Archive/Zip.php'); // imports
-
- if (file_exists('test.zip')) {
- $obj = new Archive_Zip('test.zip'); // name of zip file
- } else {
- die('File does not exist');
- }
-
- if ($obj->delete(array('by_preg' => "/.*doc$/"))) { // all DOC files
- echo 'Deleted successfully!';
- } else {
- echo 'Error in file deletion';
- }
- ?>
As shown in the preceding example, the PEAR Archive_Zip class has many purposes. It only requires a few lines of code to allow you to execute complicated interactions with ZIP files. I hope the above sample script will inspire you to show you how to use this class in your daily development activities and interest you in experimenting with it. Happy Programming