如何在 PHP 中使用 HTTP 缓存标头 [英] How to use HTTP cache headers with PHP

查看:46
本文介绍了如何在 PHP 中使用 HTTP 缓存标头的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个 PHP 5.1.0 网站(实际上它是 5.2.9 但它也必须在 5.1.0+ 上运行).

I have a PHP 5.1.0 website (actually it's 5.2.9 but it must also run on 5.1.0+).

页面是动态生成的,但其中许多页面大多是静态的.静态是指内容不会改变,但围绕内容的模板"会随着时间而改变.

Pages are generated dynamically but many of them are mostly static. By static I mean the content don't change but the "template" around the content can change over time.

我知道他们已经有几个缓存系统和 PHP 框架,但我的主机没有安装 APC 或 Memcached,我没有为这个特定项目使用任何框架.

I know they are several cache systems and PHP frameworks already out there, but my host don't have APC or Memcached installed and I'm not using any framework for this particular project.

我希望页面被缓存(我认为默认情况下 PHP禁止"缓存).到目前为止,我正在使用:

I want the pages to be cached (I think by default PHP "disallow" cache). So far I'm using:

session_cache_limiter('private'); //Aim at 'public'
session_cache_expire(180);
header("Content-type: $documentMimeType; charset=$documentCharset");
header('Vary: Accept');
header("Content-language: $currentLanguage");

我阅读了很多教程,但我找不到简单的东西(我知道缓存很复杂,但我只需要一些基本的东西).

I read many tutorials but I can't find something simple (I know cache is something complex, but I only need some basic stuff).

什么是必须"发送标题以帮助缓存?

What are "must" have headers to send to help caching?

推荐答案

您可能想使用 private_no_expire 而不是 private,但为您知道的内容设置一个长过期时间不会改变并确保您处理类似于 Emil 帖子的 if-modified-sinceif-none-match 请求.

You might want to use private_no_expire instead of private, but set a long expiration for content you know is not going to change and make sure you process if-modified-since and if-none-match requests similar to Emil's post.

$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、语言和时间戳的校验和,例如

Where $etag could be a checksum based on the content or the user ID, language, and timestamp, e.g.

$etag = md5($language . $timestamp);

这篇关于如何在 PHP 中使用 HTTP 缓存标头的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆