gzip压缩是一种很好的页面压缩传送方式,我们经常会在服务器端打开了,这样一个100K的文件通过gzip压缩之后可能只有20KB不到,下面我来介绍一下gzip压缩检测与开启方法.
如何打开gzip压缩传输呢?
apache,第1步,代码如下:
LoadModule deflate_module modules/mod_deflate.so
LoadModule headers_module modules/mod_headers.so
然后在http.conf加如下例代码:
- # BEGIN GZIP
- #apache开启gzip压缩,前提要装gzip模块哦
- <ifmodule mod_deflate.c>
- AddOutputFilterByType DEFLATE text/text text/html
- text/plain text/xml text/css application/x-javascript
- application/javascript
- </ifmodule>
- # END GZIP
如果你是nginx服务器也可参考下面代码:
- #nginx开启gzip压缩,放在location内
- gzip on;
- gzip_min_length 1000;
- gzip_buffers 4 8k;
- gzip_http_version 1.1;
- gzip_types text/text text/html text/plain text/xml
- text/css application/x-javascript application/javascript;
现在重启一下apache或nginx 即可,那么要如何检查是否正确开启gzip呢,我们可使用下面php代码:
-
-
- header('Content-Type:text/html;charset=utf-8' );
- $url = 'http://www.111cn.net';
- $file = fopen($url, "rb");
-
- $bin = fread($file, 2);
- fclose($file);
- $strInfo = @unpack("C2chars", $bin);
- $typeCode = intval($strInfo['chars1'].$strInfo['chars2']);
- $isGzip = 0;
- switch ($typeCode)
- {
- case 31139:
-
- $isGzip = 1;
- break;
- default:
- $isGzip = 0;
- }
- $url = $isGzip ? "compress.zlib://".$url:$url; // 三元表达式
- $mierHtml = file_get_contents($url);
- $mierHtml = iconv("gbk","utf-8",$mierHtml);
- echo $mierHtml;
-
- <?php
-
-
-
- $ch = curl_init("http://www.111cn.net/");//url不能有转向
- curl_setopt($ch,CURLOPT_HTTPHEADER,array('Accept-Encoding: gzip, deflate'));
- curl_setopt($ch, CURLOPT_HEADER, 1);
- curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
- $buffer = curl_exec($ch);
- $curl_info = curl_getinfo($ch);
- curl_close($ch);
- $header_size = $curl_info["header_size"];
-
- $headers = substr($buffer, 0, $header_size);
-
- $body = substr($buffer, $header_size);
-
-
- function getEncoding(&$headers){
- $arr=explode("rn",trim($headers));
- array_shift($arr);
- foreach($arr as $header){
- list($k,$v)=explode(':',$header);
- if ('content-encoding'==strtolower($k)){
- return trim($v);
- }
- }
- return false;
- }
-
- $encoding=getEncoding($headers);
-
- if ($encoding) {
- echo "Using: ".$encoding;
- }else{
- echo "None";
- }
-
- ?>
|