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

1. GZIP介绍javascript

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

HTTP协议上的GZIP编码是一种用来改进WEB;应用程序性能的技术,Web开发中经过GZIP压缩页面来下降网站的流量,并且GZIP不会占用不少CPU。整体来考虑,启用GZIP仍是很是划算的。经过HTTP头,咱们能够知道浏览器是否支持GZIP压缩。通常是经过Accept-Encoding来查看,若是是:css

Accept-Encoding:gzip,deflate,则代表支持mod_gzip和mod_deflatehtml

2. Apache和 PHP开启GZIP的方法java

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

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

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

服务器默认不支持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

相关文章
相关标签/搜索