简体   繁体   English

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

[英]Browser Cache Control System in Php

i'm trying to build a browser cache control system written in PHP. 我正在尝试构建一个用PHP编写的浏览器缓存控制系统。

More in the deep, i'd like to serve every browser request with Php, to generate the right HTTP Response Header an to generate an HTTP 200 or an HTTP 304 Not Modified at the right time. 更深层次的,我想用Php为每个浏览器请求提供服务,以生成正确的HTTP响应标头,以便在正确的时间生成HTTP 200HTTP 304 Not Modified

The big question is: how can i delegate PHP to check if a resources is an HTTP 200 or an HTTP 304 ? 最大的问题是:我如何委托PHP来检查资源是HTTP 200还是HTTP 304?

Here's some sample code for managing browser caching for a page served with PHP. 下面是一些用于管理PHP服务页面的浏览器缓存的示例代码。 You'll need to determine a timestamp $myContentTimestamp that indicates the last modified time of the content on your page. 您需要确定一个时间戳$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);
}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM