我有这样的代码:
<?php
// Include this function on your pages
function print_gzipped_page() {
global $HTTP_ACCEPT_ENCODING;
if( headers_sent() ){
$encoding = false;
}elseif( strpos($HTTP_ACCEPT_ENCODING, 'x-gzip') !== false ){
$encoding = 'x-gzip';
}elseif( strpos($HTTP_ACCEPT_ENCODING,'gzip') !== false ){
$encoding = 'gzip';
}else{
$encoding = false;
}
if( $encoding ){
$contents = ob_get_contents();
ob_end_clean();
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);
print($contents);
exit();
}else{
ob_end_flush();
exit();
}
}
// At the beginning of each page call these two functions
ob_start();
ob_implicit_flush(0);
// Then do everything you want to do on the page
?>
<html>
<body>
<p>This should be a compressed page.</p>
</html>
<body>
<?
// Call this function to output everything as gzipped content.
print_gzipped_page();
?>
但是当我查看页面源代码时,我没有看到压缩代码。怎么了?
怎么了?
也许什么都没有。GZIP压缩在服务器和浏览器之间是一个完全透明的过程。服务器将压缩数据,浏览器将自动解压缩数据。在最终结果(= HTML页面的源代码)中,什么都不会改变。
使用Firebug或Chrome开发者工具等工具查看响应是否被压缩。
在Chrome的开发者工具的"网络"选项卡中,压缩后的响应看起来像这样:
http://fhc.quickmediasolutions.com/image/- 1775578843. - png
在浏览器中查看源代码时,您将始终看到解压后的版本。
使用apache mod_deflate更加有效和舒适…http://httpd.apache.org/docs/2.0/mod/mod_deflate.html
附带提示:在移动设备上,我注意到gzip无法处理某些资产,最终发现这些资产位于应用程序缓存中,因此根本无法从服务器检索到它们。不幸的是,Chrome审计还不够聪明,无法知道缓存的资产不需要压缩,并将其报告为问题。
也许这可能帮助。
<?php
function gzip_output() {
$HTTP_ACCEPT = $_SERVER['HTTP_ACCEPT_ENCODING'];
if (headers_sent()) {
$encoding = false;
} elseif (strpos($HTTP_ACCEPT, 'x-gzip') !== false) {
$encoding = 'x-gzip';
} elseif (strpos($HTTP_ACCEPT, 'gzip') !== false) {
$encoding = 'gzip';
} else {
$encoding = false;
}
if ($encoding) {
$contents = ob_get_contents();
ob_end_clean();
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();
} else {
ob_end_flush();
exit();
}
}
// At the beginning of each page call these two functions
ob_start();
ob_implicit_flush(0);
// Then do everything you want to do on the page
?>
<html>
<body>
<p>This should be a compressed page.</p>
</html>
<body>
<?
// Call this function to output everything as gzipped content.
gzip_output();
?>