Php中的浏览器缓存控制系统

时间:2012-11-23 15:50:19

标签: php http-headers browser-cache http-status-code-304

我正在尝试构建一个用PHP编写的浏览器缓存控制系统。

更深层次的,我想用Php为每个浏览器请求提供服务,以生成正确的HTTP响应标头,以生成 HTTP 200 或< em> HTTP 304 Not Modified 在合适的时间。

最大的问题是:我如何委托PHP来检查资源是HTTP 200还是HTTP 304?

1 个答案:

答案 0 :(得分:2)

以下是一些用于管理使用PHP提供的页面的浏览器缓存的示例代码。您需要确定一个时间戳$myContentTimestamp,表示您网页上内容的上次​​修改时间。

// put this line above session_start() to disable PHP's default behaviour of disabling caching if you're using sessions
session_cache_limiter('');

$myContentTimestamp = 123456789; // here, get the last modified time of the content on this page, ex. a DB record or file modification timestamp

// browser will send $_SERVER['HTTP_IF_MODIFIED_SINCE'] if it has a cache of your page
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= $myContentTimestamp) {
    // browser's cache is the latest version, so tell the browser there is no newer content and exit
    header('HTTP/1.1 304 Not Modified');
    header('Last-Modified: ' . date("D M j G:i:s T Y", $myContentTimestamp));
    die;
} else {
    // tell the browser the last change date of this page's content
    header('Last-Modified: ' . date("D M j G:i:s T Y", $myContentTimestamp));
    // tell the browser it has to ask if there are any changes whenever it shows this page
    header("Cache-Control: must-revalidate");

    // now show your page
    echo "hello world! This page was last modified on " . date('r', $myContentTimestamp);
}