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

查看:100
本文介绍了如何在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.

我想要缓存页面(I默认情况下认为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 而不是私人,但设置您知道不会更改的内容的过期时间长,并确保您处理 if-modified-since if-none-match 请求类似于Emil的帖子。

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天全站免登陆