下面是http头
http://www.google.com/
GET / HTTP/1.1
Host: www.google.com
User-Agent: Mozilla/5.0 (Windows; U; Windows NT 5.1; zh-CN; rv:1.8.0.5) Gecko/20060719 (FoxPlus) Firefox/1.5.0.5
Accept: text/xml,application/xml,application/xhtml+xml,tex t/html;q=0.9,text/plain;q=0.8,image/png,*/*;q=0.5
Accept-Language: zh-cn,zh;q=0.5
Accept-Encoding: gzip,deflate
Accept-Charset: gb2312,utf-8;q=0.7,*;q=0.7
Keep-Alive: 300
Connection: keep-alive
HTTP/1.x 200 OK
Date: Thu, 03 Dec 2009 09:04:14 GMT
Expires: -1
Cache-Control: private, max-age=0
Content-Type: text/html; charset=UTF-8
Content-Encoding: gzip
为什么需要程序员自己决定什么时候启用gzip传输?因为调用gzip会消耗一定 的系统资源,所以至于究竟要如何操作,apache或者说webserver将控制权交给了程序员。
PHP如何使用gzip压缩
1:用.htaccess文件实现
在.htaccess加入如下代码
php_flag zlib.output_compression on
php_value zlib.output_compression_level 2
2:用PHP代码实现
//启用GIP
//判断浏览器是否支持gzip 以及 判断服务器是否载入gzip模块
if(ereg('gzip',$_SERVER['HTTP_ACCEPT_ENCODING']) && Extension_Loaded('zlib'))
{
Ob_Start('ob_gzhandler');
Header("Content-type: text/html");
}
这里还有更加详细的介绍 http://www.xueit.com/html/2009-04/22_1062_00.html
This should be a compressed page.
压缩css的实例:
首先新建一个gzip-css.php文 件,代码如下
<?php
ob_start ("ob_gzhandler");
header("Content-type: text/css; charset: UTF-8");
header("Cache-Control: must-revalidate");
$offset = 60 * 60 ;
$ExpStr = "Expires: " .
gmdate("D, d M Y H:i:s",
time() + $offset) . " GMT";
header($ExpStr);
?>
.htaccess设置如下
AddHandler application/x-httpd-php .css
php_value auto_prepend_file gzip-css.php
php_flag zlib.output_compression Onob_start详解
ob_start ([ callback $output_callback [, int $chunk_size [, bool $erase ]]] )
output_callback表示回调函数,该回调函数接受的参数是缓冲区的内容,返回的值也是缓冲区的内容
<?php
function callback($buffer)
{
// replace all the apples with oranges
return (str_replace("apples", "oranges", $buffer));
}
ob_start("callback");
?>
<html>
<body>
<p>It's like comparing apples to oranges</p>
</body>
</html>
<?php
ob_end_flush();
?>
注意:虽然可以在APACHE里设置对任何CSS以及JS文件进行ZIP压缩,但是如果每次对所有的CSS以及 JS,HTML文件进行GZIP压缩的确是能加快传输速度,但是!却会增加服务器的负荷,因为启用gzip压缩不单单要耗费内存,还要耗费CPU资源。最 好的办法是先通过gzip工具将JS CSS文件压缩,然后再直接使用