How to Use PHP scripts and PEAR classes to create ZIP files

Source: Internet
Author: User
Tags create zip
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

 
 
  1. <?php 
  2. include ('Archive/Zip.php');        // imports 
  3.  
  4. $obj = new Archive_Zip('test.zip'); // name of zip file 
  5.  
  6. $files = array('mystuff/ad.gif', 
  7.                'mystuff/alcon.doc', 
  8.                'mystuff/alcon.xls');   // files to store 
  9.  
  10. if ($obj->create($files)) { 
  11.     echo 'Created successfully!'; 
  12. } else { 
  13.     echo 'Error in file creation'; 
  14. ?>

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

 
 
  1. <?php 
  2. include ('Archive/Zip.php');        // imports 
  3.  
  4. $obj = new Archive_Zip('test.zip'); // name of zip file 
  5.  
  6. $files = $obj->listContent();       // array of file information 
  7.  
  8. foreach ($files as $f) { 
  9.     foreach ($f as $k => $v) { 
  10.         echo "$k: $v\n"; 
  11.     } 
  12.     echo "\n"; 
  13. ?>

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

 
 
  1. filename: mystuff/alcon.xls 
  2. stored_filename: mystuff/alcon.xls 
  3. size: 113664 
  4. compressed_size: 35902 
  5. mtime: 1141996836 
  6. comment: 
  7. folder: 
  8. index: 0 
  9. 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

 

 
 
  1. <?php 
  2. include ('Archive/Zip.php');        // imports 
  3.  
  4. if (file_exists('test.zip')) { 
  5.     $obj = new Archive_Zip('test.zip'); // name of zip file 
  6. } else { 
  7.     die('File does not exist'); 
  8.  
  9. $files = array('otherstuff/montecarlo.png');   // additional files to store 
  10.  
  11. if ($obj->add($files)) { 
  12.     echo 'Added successfully!'; 
  13. } else { 
  14.     echo 'Error in file addition'; 
  15. ?> 

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

 

 
 
  1. <?php 
  2. include ('Archive/Zip.php');        // imports 
  3.  
  4. if (file_exists('test.zip')) { 
  5.     $obj = new Archive_Zip('test.zip'); // name of zip file 
  6. } else { 
  7.     die('File does not exist'); 
  8.  
  9. $files = array('mystuff/ad.gif', 'otherstuff/montecarlo.png');   // files to delete 
  10.  
  11. if ($obj->delete(array('by_name' => $files))) { 
  12.     echo 'Deleted successfully!'; 
  13. } else { 
  14.     echo 'Error in file deletion';      
  15. ?> 

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

 

 
 
  1. <?php 
  2. include ('Archive/Zip.php');        // imports 
  3.  
  4. if (file_exists('test.zip')) { 
  5.     $obj = new Archive_Zip('test.zip'); // name of zip file 
  6. } else { 
  7.     die('File does not exist'); 
  8.  
  9. if ($obj->delete(array('by_preg' => "/.*doc$/"))) { // all DOC files 
  10.     echo 'Deleted successfully!'; 
  11. } else { 
  12.     echo 'Error in file deletion';     
  13. ?> 

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

Related Article

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.