How to create a zip file with PHP scripts and pear classes

Source: Internet
Author: User
Tags foreach include pear regular expression zip zip archive file

When developing Web applications, it is very likely that you will encounter file--csv data in different formats, password files, XML-encoded content, and different forms of binary data. Your PHP scripts will need to interact with these files frequently, reading data from them and writing data to them. Because there are so many formats of files to process, so you do not accidentally PHP has a number of types of built-in functions and external libraries, to connect and use almost all you can name the file format.

This guide is about such a file format that it is possible for application developers to encounter this file almost every day: the ZIP format. Typically this format is used to transfer files through e-mail and remote connections, to compress multiple files into a single file, thereby reducing the size of the file's hard disk space and making it easier to move them. PHP can read and create these zip files through its zziplib plug-in and Pear's Archive_zip class.

I will assume that you already have the normal Apache, installed PHP, and that the Pear Archive_zip class classes are installed correctly.

Note: You can install the Pear Archive_zip package directly from the Web, either download it or use the instructions provided.

Create a ZIP archive file

Let's start with a simple example: dynamically creating a ZIP file that includes several other files. Start with the script in List A.

List A

<?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 ';
}
?>

The script is very simple, but it is worth looking at carefully:

First, the first step is to create an instance of the Archive_zip class, and then initialize it with the path and name of the profile you want to create. In this example, the file is named Test.zip, located in the current directory.

Next, initialize an array that lists the files that will be compressed, along with their location on the hard disk; These locations are included in absolute or relative terms, but a key consideration is that the script has read access to those files or disk locations.

Finally, the Create () method is used to actually build the archive file by compressing and merging the specified files. This method takes the file list as input, and then returns a Boolean logical value indicating whether the profile was created successfully. Note It is important that the script must have write privileges in the directory where the file was created, otherwise the Create () method will fail; This is a common error that most beginners fail.

Now, after modifying the source file list and destination file location to reflect your local system configuration, try running the script above. If all goes well, archive_zip should be able to find the files that you have listed that are compressed into a zip file called Test.zip.

View the contents of a zip archive file

So how do you see the contents of the existing Zip file? Archive_zip lets allows you to do this by using its listcontent () method. Here 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 the listcontent () is a structure array of arrays, each representing a single file in the profile. Typically, each element holds related information, such as the name of the corresponding file, its index position, status, size (after compression and compression), and the time of the most recent modification. You can easily extract this information with a loop, and you can also reformat it in the same way as List B, making it better to transmit. Here 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 profile

An interesting feature of the Archive_zip class is that it can add new files to an existing profile through the Add () method. To illustrate this, 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, the program to add a new file to an existing profile is very similar to creating a new profile: Initializes a new Archive_zip object to the file that the question mark represents, creates an array that represents the list of files that will be added, and then enters the array into add () Method. As with the Create () method, add () returns a Boolean logical signal indicating whether the addition was successful. As before, a major problem is to remember to have sufficient permissions: Make sure that the script has the appropriate permissions to read the source file and write the newly compressed profile back to the hard drive.

Delete a file from an existing zip profile

As with adding files, you can also delete files. The Archive_zip class has a Delete () method that allows you to remove files from an existing archive file. Listing e illustrates this point.

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, you create an array of files to be deleted and then enter them in the Delete () method. Note the special parameter "By_name" in the Delete () call: This tells Archive_zip to delete only those files that exactly match the filename. If the deletion succeeds, the delete () method returns True.

In addition to this form of selective deletion, the Delete () method also supports large-scale destruction of files that match a particular type or regular expression. With the "By_ereg" or "By_preg" parameters, both Perl and PHP's regular expressions are supported. List F is an example of how to use this method to delete all the *.doc files in a file by using Perl's regular expressions.

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 example above, pear's Archive_zip class uses a lot of lines of code, allowing you to perform some fairly complex interactions with zip files. Hopefully, the example script above will inspire you to tell you how to use this class in your daily development activities and give you an interest in experimenting with it. I wish you a happy programming!

Please contact the site, timely note your name. Contact Email: edu#chinaz.com (change # to @).



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.