0

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

更深入地讲,我想使用 Php 为每个浏览器请求提供服务,以生成正确的 HTTP 响应标头并在正确的时间生成HTTP 200或未修改的 HTTP 304

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

4

1 回答 1

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);
}
于 2012-11-23T16:02:54.063 回答