当前位置: 首页 > 图文教程 > 网络编程 > PHP > 页面压缩gzip的运用

PHP
MYSQL版本大于4.1问题 - PHPchina
怎么让用户点击一个连接后,把一个图片另存了 - PHPchina
武汉10月15日Phper聚会召集!!! - PHPchina
php如果不等待exec执行的程序创建的子进程? - PHPchina
哪位知道DISCUZ处理防SQL注入的代码是哪部分 - PHPchina
求教!我实在不知道哪里问题,在线等ing - PHPchina
怎样结束用户某一进程 - PHPchina
比对用户名密码能不能这样写? - PHPchina
求助:如何在PHP+mysql中实现数据备份? - PHPchina
大家看看这个配置对吗 - PHPchina
如何禁止require当前文件 - PHPchina
无法将回调函数放在类中? - PHPchina
村里 PHP代码高亮是怎么实现的? - PHPchina
apache安装后.服务里没有apache2这个服务! - PHPchina
请教一个小问题 - PHPchina
config.php里面是不是应该把多数参数设置为常量而不是变量? - PHPchina
请教高手一个问题 - PHPchina
如何让百度收录我的网站 ?? - PHPchina
谁能给个注入的简单语句? - PHPchina
求PHP站内搜索思路 - PHPchina

PHP 中的 页面压缩gzip的运用


出处:互联网   整理: 软晨网(RuanChen.com)   发布: 2009-11-03   浏览: 109 ::
收藏到网摘: n/a

http1.1支持gzip编码的数据,所以,通过GZIP来实现页面压缩。在PHP中,我所知道的有两种方法使用GZIP,一种是PHP自带的,不过,要你所用的服务器支持才行!还有一种,呵呵,从网上搜索来的,在这儿就献给大家了。

<?php 
ob_start();//打开输出缓冲 
ob_implicit_flush(0);// 
//*****************************************************************// 
//函数名:canGzip() 
//作用:检查客户浏览器是否支持gzip,x-gzip编码 
//参数: 
//返回值:支持的编码类型"gzip", "x-gzip", 返回false代表不支持 
//*****************************************************************// 
function canGzip() 

//if (headers_sent() || connection_status) 
//return false; 
 
if (strpos('King'.$_SERVER["HTTP_ACCEPT_ENCODING"], 'gzip') !== false) 
return "gzip"; 
 
if (strpos('King'.$_SERVER["HTTP_ACCEPT_ENCODING"], 'x-gzip') !== false) 
return "x-gzip"; 
 
return false; 

 
//*****************************************************************// 
//函数名:doGzipOut($level, $debug) 
//作用:对输出缓冲的数据进行压缩并输出 
//参数:$level代表压缩级别, 0 = 不压缩, 9 = 最大压缩率 
// $debug代表是否输出调试信息, 1 = 输出, 0 = 不输出 
//返回值: 
//*****************************************************************// 
function doGzipOut($level = 1, $debug = 0) 

$ENCODING = canGzip(); 
if ($ENCODING) 

echo "n<!-- Use compress $ENCODING -->n"; 
$contents = ob_get_contents(); 
ob_end_clean(); 
 
if ($debug) 

$s = "<p>Not compress length: ".strlen($contents); 
$s .= "<br/>Compressed length: ".strlen(gzcompress($contents,$level)); 
$contents .= $s; 

 
header("Content-Encoding: $ENCODING"); 
echo "x1fx8bx08x00x00x00x00x00"; //??? 
$size = strlen($contents); 
$crc = crc32($contents); 
$contents = gzcompress($contents, $level); 
$contents = substr($contents, 0, strlen($contents) - 4); //??? 
echo $contents; 
echo pack('V',$crc); 
echo pack('V',$size); 
exit; 

else 

ob_end_flush(); 
exit(); 


?>
 使用方法: ------------Start of file----------
|< ?
| include('gzipOut.php');
|? >
|<HTML>
|... the page ...
|</HTML>
|< ?
| echo "............"
|
| doGzipout();
|? >
-------------End of file-----------