【问题标题】:Browser Cache Control System in PhpPHP中的浏览器缓存控制系统
【发布时间】:2012-11-23 15:50:18
【问题描述】:

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

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

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

【问题讨论】:

  • 任何网络服务器都为静态文件执行此操作。如果你想用 php 来做,请检查文件中的哈希和时间戳

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


【解决方案1】:

这里有一些示例代码,用于管理使用 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);
}

【讨论】:

    猜你喜欢
    • 2011-07-17
    • 2015-02-07
    • 2018-08-22
    • 1970-01-01
    • 2023-04-01
    • 1970-01-01
    • 2010-12-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多