Gzip和Cache PHP代码

时间:2009-10-05 14:11:42

标签: php

这是我的PHP代码

$phpver = phpversion();

$useragent = (isset($_SERVER["HTTP_USER_AGENT"]) ) ? $_SERVER["HTTP_USER_AGENT"] : $HTTP_USER_AGENT;
$do_gzip_compress = FALSE;

if ($phpver >= '4.0.4pl1' && (strstr($useragent,'compatible') || strstr($useragent,'Gecko'))) {
    if (extension_loaded('zlib')) {
        ob_start('ob_gzhandler');
    }
} 

header('Content-type: text/javascript;charset=utf-8');
header('Expires: '.gmdate("D, d M Y H:i:s", time() + 3600*24*365).' GMT');

echo "TEST";

我基本上想要永久地缓存内容(在客户端)以及gzip它。但是我不确定以上是否是最好的方法。我不想使用任何第三方脚本。我的客户端缓存标题是否足够?我需要添加更多吗?此外,这会干扰Apache的本机gzipping(在服务器上打开) - 它会gzip两次吗?

感谢您的时间。

3 个答案:

答案 0 :(得分:1)

ob_gzhandler会自动检测用户浏览器是否与gz兼容。

它还会自动修改标题。

它不会检测apache是​​否正在运行mod_deflate或mod_gzip(无论如何谁会说你使用Apache!)

if(!ob_start("ob_gzhandler")) ob_start();

/* insert code here then flush the buffer to $buffer */

    $cacheTime = time(); // or the file date of your static file

    $gmt_mtime = gmdate('D, d M Y H:i:s', $cacheTime ) . ' GMT';
    header("Content-type: text/css; charset=utf-8");
    header("Last-Modified: " . $gmt_mtime ,true);
    header('Content-Length: ' . strlen($buffer),true);
    header("Expires: " . gmdate("D, d M Y H:i:s", $cacheTime + $seconds) . " GMT",true);
    header("Cache-Control: no-store, no-cache, must-revalidate, proxy-revalidate",true);
    header("Cache-Control: post-check=0, pre-check=0", FALSE);

echo $buffer;

答案 1 :(得分:0)

如果您具有root访问权限,请编辑php.ini并添加以下内容以自动g​​zip您的php页面。

zlib.output_compression = On
zlib.output_compression_level = 1

然后,您的实际php页面可以是:

<?php
$expires = 3600*24*365;
header("Cache-Control: maxage=".$expires);
header('Expires: ' . gmdate('D, d M Y H:i:s', time()+$expires) . ' GMT');

echo 'test';
?>

答案 2 :(得分:0)

如果客户端的浏览器不支持gzip编码,ob_start('ob_gzhandler')将返回false(并且不会打开输出缓冲),这样做不是什么大问题,因此您可以取消用户代理测试。