一、php gzip扩展实现文件压缩
<?php
function maketime() {
list($usec,$sec) = explode(" ",microtime());
return (float)$sec + (float)$usec;
}
$start = maketime(); //计算执行时间的
$open = 1; //是否打开
$gzip_client_support = strstr($_SERVER['HTTP_ACCEPT_ENCODING"],"gzip"); //验证客户端是否支持gzip解压缩
if(extension_loaded("zlib") && $open && $gzip_client_support && $check=1) ob_start("ob_gzhandler");
//确认php已安装了zlib扩展
for($i=1;$i<1000000;$i++) {
echo $i;
}
echo "<br>";
$end = maketime();
echo ($end - $start)*1000;
if(isset($check) && $check) ob_end_flush();
?>
//通过开启$open 可以看到节省很多网页加载时间。
//其实ob_start("")可以自定义函数,
<?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();
?>
//输出 It's like comparing oranges to oranges.
可以利用gzencode实现 ob_start("ob_gzhandler");
例子,php gzip模块压缩页面:
<?php ob_start(’ob_gzip’); ?>
<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN" "http://www.w3.org/TR/xhtml1/DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=gb2312" />
<title>无标题文档</title>
</head>
<body>
</body>
</html>
<?php
ob_end_flush();
//压缩函数
function ob_gzip($content){
if(!headers_sent()&&extension_loaded("zlib")&&strstr($_SERVER["HTTP_ACCEPT_ENCODING"],"gzip")){
$content = gzencode($content,9);
header("Content-Encoding: gzip");
header("Vary: Accept-Encoding");
header("Content-Length: ".strlen($content));
}
return $content;
}
?>
//上面两种方法,都是针对动态php,如果是静态html怎么能实现gzip呢,这个需要用apache的mod_gzip模块了。