我有一个 PHP 5.1.0 网站(实际上是 5.2.9,但它也必须在 5.1.0+ 上运行)。
页面是动态生成的,但其中许多大多是静态的。静态是指内容不会改变,但内容周围的"template"会随着时间而改变。
我知道他们已经有几个缓存系统和 PHP 框架,但我的主机没有安装 APC 或 Memcached,我没有为这个特定项目使用任何框架。
我希望页面被缓存(我认为默认情况下 PHP“不允许”缓存)。到目前为止,我正在使用:
session_cache_limiter('private'); //Aim at 'public'
session_cache_expire(180);
header("Content-type: $documentMimeType; charset=$documentCharset");
header('Vary: Accept');
header("Content-language: $currentLanguage");
我阅读了很多教程,但找不到简单的东西(我知道缓存很复杂,但我只需要一些基本的东西)。
什么是“必须”发送 header 以帮助缓存?
最佳答案
您可能想要使用 private_no_expire
而不是 private
,但为您知道不会更改的内容设置一个较长的过期时间,并确保您处理 if -modified-since
和 if-none-match
请求类似于 Emil 的帖子。
$tsstring = gmdate('D, d M Y H:i:s ', $timestamp) . 'GMT';
$etag = $language . $timestamp;
$if_modified_since = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : false;
$if_none_match = isset($_SERVER['HTTP_IF_NONE_MATCH']) ? $_SERVER['HTTP_IF_NONE_MATCH'] : false;
if ((($if_none_match && $if_none_match == $etag) || (!$if_none_match)) &&
($if_modified_since && $if_modified_since == $tsstring))
{
header('HTTP/1.1 304 Not Modified');
exit();
}
else
{
header("Last-Modified: $tsstring");
header("ETag: \"{$etag}\"");
}
其中 $etag
可以是基于内容或用户 ID、语言和时间戳的校验和,例如
$etag = md5($language . $timestamp);
关于php - 如何在 PHP 中使用 HTTP 缓存 header ,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/1971721/