本文主要和大家分享PHP如何开启gzip提升网页响应速度,希望能帮助到大家。
1、apache开启gzip(此方式需要重启服务器):
a.开启模块:LoadModule deflate_module modules/mod_deflate.so
LoadModule headers_module modules/mod_headers.so
b.httpd.conf中增加 DeflateCompressionLevel 9
AddOutputFilterByType DEFLATE text/html text/plain text/xml application/json application/xml
AddOutputFilter DEFLATE js css
AddOutputFilter INCLUDES .shtml .htm .xml .php .html
c.重启服务器
2、php开启gzip
原理:header("Content-Encoding: gzip");echo gzencode('songjiankang');
示例1:function ob_gzip ($content) // $content 就是要压缩的页面内容,或者说饼干原料{ if (! headers_sent() && // 如果页面头部信息还没有输出
extension_loaded("zlib") && // 而且zlib扩展已经加载到PHP中
strstr($_SERVER["HTTP_ACCEPT_ENCODING"], "gzip")) // 而且浏览器说它可以接受GZIP的页面 { $content = gzencode($content . " \n//此页已压缩", 9); // 此页已压缩”的注释标签,然后用zlib提供的gzencode()函数执行级别为9的压缩,这个参数值范围是0-9,0表示无压缩,9表示最大压缩,当然压缩程度越高越费CPU。
// 然后用header()函数给浏览器发送一些头部信息,告诉浏览器这个页面已经用GZIP压缩过了!
header("Content-Encoding: gzip"); header("Vary: Accept-Encoding"); header("Content-Length: " . strlen($content));
} return $content; // 返回压缩的内容,或者说把压缩好的饼干送回工作台。}ob_start('ob_gzip');
示例2:#ob_gzhandler 为php内置函数,具体参考手册ob_start('ob_gzhandler');
相关推荐: