[转]PHP通过zlib扩展实现GZIP压缩输出

1. GZIP介绍

GZIP是GNU zip的缩写,它是一个GNU自由软件的文件压缩程序,也经常用来表示gzip这种文件格式。GZIP主要用于Unix系统的文件压缩,我们经常看到的后缀为.gz的文件,它们就是GZIP格式的。GZIP的压缩效果比较明显,应用Gzip压缩网页时,网页可以压缩30%甚至更多。

HTTP协议上的GZIP编码是一种用来改进WEB;应用程序性能的技术,Web开发中通过GZIP压缩页面来降低网站的流量,而且GZIP不会占用很多CPU。总体来考虑,启用GZIP还是非常划算的。通过HTTP头,我们可以知道浏览器是否支持GZIP压缩。一般是通过Accept-Encoding来查看,如果是:

Accept-Encoding:gzip,deflate,则表明支持mod_gzip和mod_deflate

2. Apache和 PHP开启GZIP的方法

1) 更改Apache配置文件,支持mod_deflate模块

要Apache支持GZIP,Apache必须支持mod_deflate这个模块。修改Apache目录下的配置文件httpd.conf,设置LoadModule deflate_module modules/mod_deflate.so

2)两种开启压缩方式的介绍

服务器默认不支持mod_gzip、mod_deflate模块,若想通过GZIP压缩页面内容,可以考虑两种方式,开启zlib.output_compression或者通过ob_gzhandler编码的方式。

zlib.output_compression是在对网页内容压缩的同时发送数据至客户端。

ob_gzhandler是等待网页内容压缩完毕后才进行发送,相比之下前者效率更高,但需要注意的是,两者不能同时使用,只能选其一,否则将出现错误。

3) 启用GZIP压缩方法

方法一:修改Apache配置文件httpd.conf

修改Apache配置文件httpd.conf,在配置文件中添加如下代码:

<IfModule mod_deflate.c>
SetOutputFilter DEFLATE
DeflateCompressionLevel 5
AddOutputFilterByType DEFLATE text/html text/css image/gif image/jpeg image/png application/x-javascript
</IfModule>

  

方法二:修改php 配置文件php.ini

zlib.output_compression = Off Off更改成On

zlib.output_compression_level = -1 zlib.output_compression_level 建议参数值是1~5,6以实际压缩效果提升不大,cpu占用却是几何增长。

方法三:通过.htaccess文件开启,服务器必须开启伪静态

<IfModule mod_deflate.c>

    # Insert filter on all content
    SetOutputFilter DEFLATE
    # Insert filter on selected content types only
    AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css text/javascript

    # Netscape 4.x has some problems...
    BrowserMatch ^Mozilla/4 gzip-only-text/html

    # Netscape 4.06-4.08 have some more problems
    BrowserMatch ^Mozilla/4\.0[678] no-gzip

    # MSIE masquerades as Netscape, but it is fine
    BrowserMatch \bMSIE !no-gzip !gzip-only-text/html

    # Don't compress images
    SetEnvIfNoCase Request_URI \.(?:gif|jpe?g|png)$ no-gzip dont-vary

    # Make sure proxies don't deliver the wrong content
    #Header append Vary User-Agent env=!dont-vary

</IfModule>

  

方法四:通过ob_gzhandler编码,在PHP页面开启

<?php
if(Extension_Loaded('zlib')) Ob_Start('ob_gzhandler'); 
/*
这里为PHP页面输出内容
*/

if(Extension_Loaded('zlib')) Ob_End_Flush(); 
?>

  

3. 检测网站是否开启GZIP

通过站长GZIP压缩检测功能

访问 http://tool.chinaz.com/Gzips/,输入网址,可以查看网站的是否启用GZIP压缩,网页压缩率等信息

转载自:http://www.phpmarker.com/187.html