0

PHP で書かれたブラウザ キャッシュ制御システムを構築しようとしています。

さらに深く、すべてのブラウザー リクエストを Php で処理して、適切な HTTP 応答ヘッダーを生成し、適切なタイミングでHTTP 200またはHTTP 304 Not Modifiedを生成したいと考えています。

大きな問題は、リソースが HTTP 200 か HTTP 304 かを確認するために PHP を委任するにはどうすればよいかということです。

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 に答える