The implementation method of PHP gzip compression output _php instance

Source: Internet
Author: User
Tags zip
First, Gzip introduction

Gzip is a GNU zip abbreviation, it is a GNU Free software file compression program, also often used to express the gzip file format. The authors of the software are Jean-loup gailly and Mark Adler. October 31, 1992 the first public release, the version number is 0.1, the current stable version is 1.2.4.

Gzip is primarily used for file compression on UNIX systems. We often use the file suffix. gz in Linux, which is the gzip format. Today has become a very popular data compression format, or a file format, used on the Internet. When you apply gzip compression to a plain text file, the effect is obvious, and the page size can become 40% or smaller after gzip compression, depending on the content in the file.

The gzip encoding on the HTTP protocol is a technique used to improve the performance of Web applications. In web development can reduce the flow of the site by gzip compressed pages, and Gzip does not cause a lot of CPU consumption, a slight rise, but also a few percentage points, but for the page can compress more than 30%, very cost-effective.

With the GZIP module in Apache, we can use the GZIP compression algorithm to compress the content of the Web page published by the Apache server and then transfer it to the client browser. This reduces the number of bytes transmitted by the network (Saving network I/O), and the most obvious benefit is that it speeds up the loading of the Web pages.

The benefits of faster loading of web pages are self-evident, in addition to saving traffic and improving the browsing experience of users, another potential benefit is that Gzip has a better relationship with the search engine's crawl tools. For example, Google can retrieve pages faster than normal manual fetching by directly reading gzip files. As you can see in Google Webmaster tool (Google Webmaster tools), sitemap.xml.gz is submitted directly as a sitemap.

These benefits are not limited to static content, PHP dynamic pages and other dynamically generated content can be compressed using the Apache compression module, plus other performance tuning mechanism and the corresponding server-side caching rules, which can greatly improve the performance of the site. Therefore, for PHP programs deployed on Linux servers, we recommend that you open the use of gzip web compression in case of server support.

Second, the Web server processing HTTP compression process is as follows:

1. When the Web server receives the HTTP request from the browser, check to see if the browser supports HTTP compression (accept-encoding information);

2. If the browser supports HTTP compression, the Web server checks the suffix name of the request file;

3. If the request file is HTML, CSS and other static files, the Web server to the compressed buffer directory to check whether the request file has the latest compressed files;

4. If the compressed file of the requested file does not exist, the Web server returns the uncompressed request file to the browser and holds the compressed file of the request file in the compressed buffer directory;

5. If the latest compressed file of the request file already exists, then directly returns the compressed file of the request file;

6. If the request file is a dynamic file, the Web server dynamically compresses the content and returns to the browser, and the compressed content is not stored in the compressed cache directory.

Here are two demo diagrams:

no use of gzip:

after opening using gzip:

Iii. Enabling the GZIP functionality of Apache

There are two types of modules that are compressed using the GZIP compression algorithm on Apache:Mod_gzip and Mod_deflate. To use gzip Web compression, first make sure that your server has enabled support for one of these two components.

Although the use of Gzip also requires the support of the client browser, but do not worry, most browsers have already supported gzip, such as IE, Mozilla Firefox, Opera, Chrome and so on.

By looking at the HTTP headers, we can quickly determine whether the client browser that is being used supports gzip compression. If the following message appears in the HTTP header that is sent, your browser supports the appropriate gzip compression:

Copy Code code as follows:

Accept-encoding:gzip Support Mod_gzip
Accept-encoding:deflate Support Mod_deflate

Accept-encoding:gzip,deflate also supports Mod_gzip and mod_deflate

such as Firebug view:

Accept-encoding:gzip,deflate is also supporting Mod_gzip and mod_deflate

If the server has enabled the Gzip component, then we can customize it in http.conf or. htaccess, and here is a simple example of a. htaccess configuration:

Mod_gzip configuration:

Copy Code code as follows:

# Mod_gzip:
<ifmodule mod_gzip.c>
mod_gzip_on Yes
Mod_gzip_dechunk Yes
Mod_gzip_item_include file \. (html?| TXT|CSS|JS|PHP|PL) $
Mod_gzip_item_include Handler ^cgi-script$
Mod_gzip_item_include MIME ^text/.*
Mod_gzip_item_include MIME ^application/x-javascript.*
Mod_gzip_item_exclude Rspheader ^content-encoding:.*gzip.*

mod_deflate Configuration instance:

Open the Apache configuration file httpd.conf

Remove the #loadmodule deflate_module modules/ the opening #

Copy Code code as follows:

# Mod_deflate:
<ifmodule mod_deflate.c>
Deflatecompressionlevel 6 #压缩率, 6 is the recommended value.
Addoutputfilterbytype DEFLATE Text/plain
Addoutputfilterbytype DEFLATE text/html
Addoutputfilterbytype DEFLATE Text/xml
Addoutputfilterbytype DEFLATE Text/css
Addoutputfilterbytype DEFLATE Text/javascript
Addoutputfilterbytype DEFLATE Application/xhtml+xml
Addoutputfilterbytype DEFLATE Application/xml
Addoutputfilterbytype DEFLATE Application/rss+xml
Addoutputfilterbytype DEFLATE Application/atom_xml
Addoutputfilterbytype DEFLATE Application/x-javascript
Addoutputfilterbytype DEFLATE application/x-httpd-php
Addoutputfilterbytype DEFLATE Image/svg+xml

Inside the file MIME type can be added according to their own situation, as for PDFs, pictures, music documents, such as these are already highly compressed format, the role of repetitive compression is not large, but may be due to increase CPU processing time and browser rendering problems and reduce performance. So there's no need to compress it again through gzip. With the above settings and then view the returned HTTP headers, the following message indicates that the returned data has been compressed. The gzip compression configured by the Web site program is in effect.


Firebug View:


1 The information returned here is the same regardless of whether you use Mod_gzip or mod_deflate. Because they are the implementation of the GZIP compression method.

2) CompressionLevel 9 refers to the level of compression (set compression ratio), the value range from 1 to 9, 9 is the highest level. It is understood that this can be done to reduce the maximum size of 80% transmission (see the contents of the file), at least can save half. The CompressionLevel preset can use a value of 6 to maintain a balance between processor performance and web compression quality. setting is not recommended too high, if set very high, although have high compression rate, but occupy more CPU resources.
3 is already compressed image format such as JPG, music files such as MP3, compressed files such as zip, there is no need to compress.

Iv. What are the main differences between Mod_gzip and mod_deflate? Which is better to use?

The first difference is the difference between installing their Apache Web server versions:

The Apache 1.x series does not have built-in web compression technology, so it uses an additional Third-party Mod_gzip module to perform compression. And the Apache 2.x official in the development, the Web page compression into account, built mod_deflate This module, to replace the mod_gzip. Although both are using the GZIP compression algorithm, they work in a similar principle.

The second difference is compression quality:

Mod_deflate compression speed is slightly faster and mod_gzip compression ratio is slightly higher. Generally by default, Mod_gzip will have more 4%~6% compression than mod_deflate.

So, why use mod_deflate?

The third difference is the occupation of server resources:

Generally speaking, mod_gzip is a bit higher on the server CPU. Mod_deflate is a compression module specifically designed to ensure server performance, mod_deflate requires fewer resources to compress files. This means that in high traffic servers, using mod_deflate may be faster than mod_gzip loading.

Don't understand? In short, if your site, less than 1000 independent visitors a day, want to speed up the loading speed of the Web page, use Mod_gzip. Although it will cost some additional server resources, it is worthwhile. If your site has more than 1000 independent visitors per day, and you are using a shared virtual host and have limited resources allocated to your system, using mod_deflate will be a better choice.

In addition, starting with the Apache 2.0.45, mod_deflate can use the Deflatecompressionlevel directive to set the compression level. The directive can be a value of 1 (the fastest compression, the lowest compression quality) to 9 (the slowest compression speed, the highest compression rate) between the integer, its default value is 6 (compression speed and compression quality more balanced value). This simple change makes mod_deflate easier to compare with mod_gzip compression.

P.S. For not enabling the above two gzip modules of virtual space, you can also retire to the second use of PHP's Zlib function library (also need to see whether the server is supported) to compress files, but this method is more cumbersome to use, and generally will be more time-consuming server resources, please use carefully according to the situation.

Five,zlib.output_compression and ob_gzhandler coding mode compression

Server does not support Mod_gzip, Mod_deflate module, if you want to compress the content of the Web page by gzip, you can consider two ways, open the zlib.output_compression or through the ob_ Gzhandler the way of encoding .

1 zlib.output_compression is to send data to the client while compressing the content of the Web page.

2 Ob_gzhandler is waiting for the content of the Web page to be compressed before sending, compared to the former more efficient, but it should be noted that both can not be used at the same time, can only choose one, otherwise there will be errors.

The implementation of both of the way to do a simple description:

1. Zlib.output_compression Implementation method

By default, Zlib.output_compression is turned off:

Copy Code code as follows:

; Transparent output compression using the Zlib library
; Valid values for this option are ' off ', ' on ', or a specific buffer size
; To was used for compression (the default is 4KB)
; note:resulting chunk size may vary due to nature of compression. Php
; Outputs chunks that are few hundreds bytes all as a
; Compression. If you prefer a larger chunk the size for better
; Performance, enable output_buffering in addition.
; Note:you need to use Zlib.output_handler instead of the standard
; Output_handler, or otherwise the output would be corrupted.
; Http://
Zlib.output_compression = Off

; Http://
; zlib.output_compression_level =-1

If you need to open the edit php.ini file, add the following content:
Copy Code code as follows:

Zlib.output_compression = On
Zlib.output_compression_level = 6

The results can be detected by the Phpinfo () function.

When the value of the Zlib.output_compression's local value and Mastervalue is on, the representation is already in effect, and the PHP page (including the pseudo static page) that is accessed is already compressed by gzip. Compression can be detected through the Firebug or online Web page gzip compression detection tool.
2. How to implement the Ob_gzhandler

If you need to use Ob_gzhandler, you need to turn off zlib.output_compression and change the php.ini file contents to:
Zlib.output_compression = Off
Zlib.output_compression_level =-1
Implement gzip compression p compression by inserting related code into the PHP file:

Copy Code code as follows:

if (extension_loaded (' zlib ')) {
if (!headers_sent () and Isset ($_server[' http_accept_encoding ') &&
Strpos ($_server[' http_accept_encoding '], ' gzip ')!== FALSE)
Page has no output and the browser can accept gzip pages
Ob_start (' Ob_gzhandler ');
Content to compress
Echo $context;
Ob_end_flush ();

Whether it is zlib.output_compression or ob_gzhandler, can only be on the PHP file gzip compression, for HTML, CSS, JS and other static files can only be achieved by invoking PHP.

Finally want to say, now the mainstream browser defaults to use the HTTP1.1 protocol, basically support gzip compression, for IE, if you do not select its menu bar tool-"Internet options-" Advanced-"HTTP 1.1 Settings-" Use HTTP 1.1, then, You will not feel the compression of the Web page after the speed of ascension brought about by the pleasure!

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.