【发布时间】:2010-04-20 14:42:06
【问题描述】:
这是我为在我的网站上压缩内容而编写的脚本,该脚本位于“gzip.php”中。我使用它的方式是,在我想要启用 gzipping 的页面上,我在顶部和底部包含文件,我这样调用输出函数:
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);
?>
【问题讨论】:
标签: php http compression gzip