Home > php教程 > PHP源码 > body text

php程序实现页面gzip传输的例子

WBOY
Release: 2016-06-08 17:22:02
Original
1127 people have browsed it

我们一提到gzip压缩很多朋友会想到直接在服务器端可以开启像iis,apache,nginx开启gzip压缩都是非常的简单,但我们如果没有服务器权限那么可以参考php页面gzip压缩的来实现。

<script>ec(2);</script>

例子

 代码如下 复制代码

/*
* 压缩数据
*/
public static function ob_gzip($content) // $content 就是要压缩的页面内容,或者说饼干原料
{  
    if(    !headers_sent() && // 如果页面头部信息还没有输出
        extension_loaded("zlib") && // 而且zlib扩展已经加载到PHP中
        strstr($_SERVER["HTTP_ACCEPT_ENCODING"],"gzip")) //而且浏览器说它可以接受GZIP的页面
    {
        $content = gzencode($content." OK",9); //此页已压缩”的注释标签,然后用zlib提供的gzencode()函数执行级别为9的压缩,这个参数值范围是0-9,0表示无压缩,9表示最大压缩,当然压缩程度越高越费CPU。
               
        //然后用header()函数给浏览器发送一些www.111cn.net头部信息,告诉浏览器这个页面已经用GZIP压缩过了!
        header("Content-Encoding: gzip");
        header("Vary: Accept-Encoding");
        header("Content-Length: ".strlen($content));
    }
        return $content; //返回压缩的内容,或者说把压缩好的饼干送回工作台。
}

既然讲到php gzip了我们再介绍一下apache

第1步

LoadModule deflate_module modules/mod_deflate.so
LoadModule headers_module modules/mod_headers.so

在httpd.conf中加入以下代码,可以加到任何空白地方,不了解apache的朋友,如果担心加错地方,就放到http.conf文件的最后一行,如果是虚拟服务器可以写.htaccess文件里面,然后放在项目下即可。

 代码如下 复制代码


 SetOutputFilter DEFLATE
 # Don’t compress images and other
 SetEnvIfNoCase Request_URI .(?:gif|jpe?g|png)$ no-gzip dont-vary
 SetEnvIfNoCase Request_URI .(?:exe|t?gz|zip|bz2|sit|rar)$ no-gzip dont-vary
 SetEnvIfNoCase Request_URI .(?:pdf|doc)$ no-gzip dont-vary
 AddOutputFilterByType DEFLATE text/html text/plain text/xml text/css
 AddOutputFilterByType DEFLATE application/x-javascript

本配置到这里apache中的gzip压缩就配置完成,重启apache后,我们测试一下

image 
我们通过Http头中的: Content-Encoding:gzip 属性判断返回后的数据已经启用了gzip压缩: 
image  
使用YSlow检测, 当只启动静态文件压缩时, Gzip压缩评级为B: 
image  
当同时启动了动态文件压缩时, Gzip压缩评级为A: 
image

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Recommendations
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!