[英]Why is php gzip output not working for me?
我有这个代码:
<?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 的开发人员工具的“网络”选项卡中,压缩响应将如下所示:
附带提示:在移动设备上,我注意到 gzip 无法处理某些资产,最终发现这些资产位于应用程序缓存中,因此根本没有从服务器检索它们。 不幸的是,Chrome 审计还不够聪明,无法知道缓存的资产不需要压缩并将它们报告为问题。
在浏览器中查看源代码时,总是会看到解压后的版本。
using apache mod_deflate is much more effective and comfortable… http://httpd.apache.org/docs/2.0/mod/mod_deflate.html
也许这可能会有所帮助。
<?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();
?>
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.