时,这是我为我的网站上,它位于“gzip.php” gzip压缩的内容写的剧本。我用它的方式是,在这里我想启用gzip压缩的网页我包括文件的顶部和底部我把这样的输出功能:损坏的数据使用gzip压缩
print_gzipped_page('javascript')
如果该文件是一个CSS文件我使用'css'作为$ type-argument,如果它的php文件没有声明任何参数,则调用该函数。该脚本在除Opera以外的所有浏览器都能正常工作,因为数据受损会导致无法解码页面。谁能告诉我我做错了什么?
<?php
function print_gzipped_page($type = false) {
if(headers_sent()){
$encoding = false;
}
elseif(strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'x-gzip') !== false){
$encoding = 'x-gzip';
}
elseif(strpos($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip') !== false){
$encoding = 'gzip';
}
else{
$encoding = false;
}
if ($type!=false) {
$type_header_array = array("css" => "Content-Type: text/css", "javascript" => "Content-Type: application/x-javascript");
$type_header = $type_header_array[$type];
}
$contents = ob_get_contents();
ob_end_clean();
$etag = '"' . md5($contents) . '"';
$etag_header = 'Etag: ' . $etag;
header($etag_header);
if ($type!=false) {
header($type_header);
}
if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and $_SERVER['HTTP_IF_NONE_MATCH']==$etag) {
header("HTTP/1.1 304 Not Modified");
exit();
}
if($encoding){
header('Content-Encoding: '.$encoding);
print("\x1f\x8b\x08\x00\x00\x00\x00\x00");
$size = strlen($contents);
$contents = gzcompress($contents, 9);
$contents = substr($contents, 0, $size);
}
echo $contents;
exit();
}
ob_start();
ob_implicit_flush(0);
?>
附加信息:如果被压缩文档的长度只有10-15个字符,则该脚本有效。
感谢您的帮助,修改后的版本:
<?php
function print_gzipped_page($type = false) {
if(headers_sent()){
$encoding = false;
}
elseif(strpos($_SERVER['HTTP_ACCEPT_ENCODING'], 'x-gzip') !== false){
$encoding = 'x-gzip';
}
elseif(strpos($_SERVER['HTTP_ACCEPT_ENCODING'],'gzip') !== false){
$encoding = 'gzip';
}
else{
$encoding = false;
}
if ($type!=false) {
$type_header_array = array("css" => "Content-Type: text/css", "javascript" => "Content-Type: application/x-javascript");
$type_header = $type_header_array[$type];
header($type_header);
}
$contents = ob_get_contents();
ob_end_clean();
$etag = '"' . md5($contents) . '"';
$etag_header = 'Etag: ' . $etag;
header($etag_header);
if (isset($_SERVER['HTTP_IF_NONE_MATCH']) and $_SERVER['HTTP_IF_NONE_MATCH']==$etag) {
header("HTTP/1.1 304 Not Modified");
exit();
}
if($encoding){
header('Content-Encoding: ' . $encoding);
$contents = gzencode($contents, 9);
}
$length = strlen($contents);
header('Content-Length: ' . $length);
echo $contents;
exit();
}
ob_start();
ob_implicit_flush(0);
?>
谢谢你,问题就迎刃而解了。我删除了压缩数据上的substr(),并用压缩文档的长度设置了Content-Length头。 – RadiantHeart 2010-04-20 15:47:50