Part 1: use the new zip Extension

Source: Internet
Author: User
Tags zip extension ziparchive silver light

/* Link from:

* Author profile: Tracy Peterson (, freelance writer, Consultant. From

* Since 1997, Tracy Peterson has been an IT project manager and Web developer.

* Head of Microsoft's MSN Search computing program. He is currently working in San Francisco.

* Finishing staff: Luo Dong


ZIP Overview

The ZIP file format introduced in 1989 deletes the blank space and redundant information in the file and packs multiple files into one package to help computer users transmit large files. ZIP was initially created by Phil Katz for the shared part program PKZIP, which is a fast, reliable and compliant compression format. These factors make ZIP a success among PC users, and their open specifications allow programmers to build ZIP files into Windows, OS X, Konqueror, and Nautilus File Manager. It is safe to use the ZIP file compression format that can be processed by almost all computers.

Compression usually has many advantages. You can reduce the file size or bind several files to an archive file. By reducing the file size, the bandwidth and storage device load will also decrease. The file size requirement is obvious, but when the only other option is to download files one by one, it is a huge advantage to bind several files together. You can create a large number of files as one download, so that you can easily deliver products or services to users.

Since ZIP can be used in almost all computers, it is a good option to use it to compress applications, especially when users download files to desktop computers. For example, Windows XP users can easily use local ZIP support, called compressed folders. When a Windows XP user downloads a ZIP file, it displays the compressed folder that the user can double-click to open. OS X, Konqueror, and Nautilus users only need to double-click the ZIP file to open the file.

Where is the space compressed?

The files selected for archive (another name of the ZIP file) are listed in the file structure, and then scaled down or compressed. All files are compressed into a ZIP file using one of the many compression algorithms, but these compression algorithms are operated in the same way: delete redundant data or blank space. This method is particularly effective when it is applied to text files that can reduce a large number of duplicate texts and punctuation marks to save space. When processing image files (such as JPEG images), compression is not so easy, because data is more difficult to reduce duplication.

There are several methods to reduce the file size, and they are all common methods for ZIP format. Every language or application that uses ZIP knows the format, and PHP is no exception. PHP will use one of these algorithms like other applications to compress files and obtain the results of any other language or program. Let's look at an example:

Let's refer to what Qiu Gill, one of my most admired historical figures, often says. The text file Winston.txt contains the following text: "You make a living by what you get; you make a life by what you give .". '

To compress the file Winston.txt, you can delete unnecessary spaces, the method is to create an index -- operate like a search engine -- replace the file component with the copy of the index and the layout of the index component. Use a very small example like this example. If there are no duplicate words, the index size will be very close to the size of the example. A word can be added to an index only when it is repeated. Therefore, this should not be a problem.

In our example, there are the following repeated words:

1. "we" is used four times

2. "make" is used twice.

3. "a" is used twice

4. "by" is used twice

5. "what" is used twice

There are still a few words to write:

1. "living"

2. "get"

3. "life"

4. "give"

If we use the index to write out our example, we get "1 2 3 living 4 5 1 get; 1 2 3 life 4 5 1 give .".

You can see that the file currently contains less information. For accuracy, you can calculate and determine the number of characters saved. The original file contains 64 characters (including punctuation marks ). If the comment in the index is reduced to a simpler content (such as 1we4), the index is reduced to 23 characters and the total number of actual string characters is 33 to 56. The file size is not significantly reduced, but if you add the remaining parts of the speech to the file, you will start to see major improvements in compression. The index will be larger, but the number of instances for each word will also increase. The index load will begin to decrease, and you will see an excellent compression rate.

On average, the compression ratio of text files is about 70%. For more complex and difficult to compress files (such as images), the compression ratio is about 10%.

What content does ZIP contain?

Because ZIP archives can have multiple files, ZIP archives have their own file structure, just like the file system on your local computer. This structure is built around entries and allows clever encoders to extract only one file from many files during decompression. This structure is very convenient when you only need one image or one text file in the archive file. This structure also maintains directory information, which is extremely useful when transmitting Web sites or other file groups with file system dependency.

In a PHP script, each file has a set of available file information. When opening a file, you can access this information in the created ZipArchive object. This information can be used for various purposes, such as checking the size of the decompressed file or creating a list of ZIP files without opening it.

Some features of php zip allow very useful methods to process these file structures. In the next example, we will show you several ways to view these features and learn how to create a ZIP file structure when creating a ZIP file.

Continue compression

Let's take a look at an example of using PHP to create a ZIP file. The sample code I will use is almost identical to the sample provided in the Manual documentation, with only a few modifications (for the ZIP function page, see references ). Let's take a look at how to create a ZIP file and view how to build the file structure correctly. We will insert the string as a file into the new ZIP file and obtain the existing file to the new ZIP file.

First, you must prepare a text file to be added to the ZIP file.

Listing 1. Testtext.txt

Had I the heavens 'embroidered cloths,

Enwrought with golden and silver light,

The blue and the dim and the dark cloths

Of night and light and the half-light,

I wocould spread the cloths under your feet:

But I, being poor, have only my dreams;

I have spread my dreams under your feet,

Tread softly because you tread on my dreams.

William Butler Yeats

You can test this code to view the results of this attempt. To test, you should cut and paste Listing 1 and put it in the same directory as the PHP script. Save this file as testtext.txt because it will be referenced in PHP code.

You can test this code to view the results of this attempt. To test, you should cut and paste Listing 1 and put it in the same directory as the PHP script. Save this file as testtext.txt because it will be referenced in PHP code.

Next, create a zip file.

Listing 2. zipcreate. php

<? PHP

$ Zip = new ziparchive ();

$ Filename = " ";

If ($ zip-> open ($ filename, ziparchive: Create )! = True ){

Exit ("cannot open <$ FILENAME> \ n ");


$ Zip-> addfromstring ("firstfile.". Time (). ". txt ",\

"This is the first file in our zip, added

Firstfile.txt. \ n ");

$ Zip-> addfromstring ("testdir/secondfile.". Time (). ". txt ",\

"This is the second file in our zip,

Added as secondfile.txt in the testdir directory. \ n ");

Echo "numfiles:". $ zip-> numfiles. "\ n ";

$ Zip-> close ();


First, create a new ZIP Archive object in the first line. After an object is created, a variable is set for the file name for later use in the script. This file name can be explicitly called each time, but setting a variable for multiple times makes it easier. Constant ziparchive: Create indicates that if a file with this name does not exist, a new file should be created. If this is the first time you run the script, a new zip file will be created. If this result does not appear, the script displays an error and exits.

Next, use the addfromstring () method, which allows you to create entries in the ZIP Archive using string data or string variables. You must create a file handle to identify the file in the ZIP file structure. In this case, firstfile.txt is used as the file name and the Creation Time is used. String data is subsequently stored. Next we will execute this operation again when processing secondfile.txt, but this time we added the directory. You can see that the file identifier secondfile.txt actually has the next level of the path. It will be displayed in the testdir directory.

We will show you the number of files in the archive, close the file, and save it as a ZIP archive for users to download. You may notice that when you continuously press Refresh or use other methods to run PHP scripts, the number of ZIP files will increase. This is because you have been opening the same file in the same directory, adding two strings as the file, and closing it again.

Figure 1. sample output of zipcreate. php

As you will notice, the new file is not actually added to the ZIP file. We need to put poetry in it so that users can get some training. Let's add it now.

Listing 3. Add an external file to

<? Php

$ Zip = new ZipArchive ();

$ Filename = " ";

If ($ zip-> open ($ filename, ZIPARCHIVE: CREATE )! = TRUE ){

Exit ("cannot open <$ filename> \ n ");


$ Zip-> addFromString ("firstfile.". time (). ". txt ",\

"This is the first file in our ZIP, added

Firstfile.txt. \ n ");

$ Zip-> addfromstring ("testdir/secondfile.". Time (). ". txt ",\

"This is the second file in our zip,

Added as secondfile.txt. \ n ");

$ Zip-> AddFile ("testtext.txt ");

Echo "numfiles:". $ zip-> numfiles. "\ n ";

$ Zip-> close ();


In this case, the path is relative, but points to the file to be added to the ZIP file and uses the AddFile () method to package it in it. If the file testtext.txt is located in the same directory, you can add it to the archive. Now you have created a new archive file using any string data and added the external file to the archive. These are the most common tasks when creating a new archive.

Open Archive

If we cannot restore normally used files from the archive, the zip file is of little use. Some programs can read files directly from the archive, but these programs must first decompress the files. The most common solution is to simply open the entire file and expand it into a single component file, and prepare these files for normal use. For our purpose, we will open the previously created ZIP file and view its content.

Listing 4. zipread. php

<? PHP

$ Zip = new ziparchive ();

$ Filename = ' ';

If ($ zip-> open ($ filename )! = TRUE ){

Exit ("cannot open <$ filename> \ n ");


Print_r ($ zip );

Var_dump ($ zip );

Echo "<br> ";

Echo "The file". $ filename. "has the following files: \ n <br> ";

For ($ I = 0; $ I <$ zip-> numFiles; $ I ++ ){

Echo "index: $ I \ n ";

Print_r ($ zip-> statIndex ($ I ));

Echo "<br> \ n ";


$ Zip-> extracelist ('./testdestination /');

$ Zip-> close ();


As before, create a new ZipArchive class instance in the variable form named $ zip. Use ZipArchive's open () method to open the created ZIP archive. The if statement is used as a simple error control. if the user fails to find the file due to a small error, the script is exited. If the file is successfully opened, the script continues to run and prints information about the ZIP file to the user.

So far, we have completed two important tasks. The files in the ZIP archive are listed one by one. Since the index array will be output from the $ zip object, a large amount of data will be obtained, including file size, checksum information. To reduce the data volume, you can view the attributes of a file in a specific index.

Once the content in the file is printed, all content will be released to the directory named testdestination. If this directory is unavailable, the system will create this directory for us. Note that if the directory already exists, or if a file with the same name already exists in the decompressed target directory, the ZIP function overwrites the original content.

We have opened the ZIP archive. By saving it to the local directory, we are ready to use the file and list the content, so we can prepare for modifying the initial ZIP file. These simple tasks are just the beginning and cannot be used for File compression for the most complex applications. Clever Use of compression can bring more convenience to all types of file transmission. The ZIP local support in PHP will solve a large number of file transfer problems.


One possible application is to upload a large number of files to the server. For example, you need to upload a photo to the photo library or upload many text files. You can simply ZIP the file and let the upload script decompress the file, without the need to upload files one by one in the upload dialog box. This saves the trouble of clicking the Browse dialog box.

Generally, it is a good idea to ZIP files that won't be directly accessed or downloaded and used again-and we finally enable PHP to have this function.

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: 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.