alesdario
alesdario

Reputation: 1894

Browser Cache Control System in Php

i'm trying to build a browser cache control system written in 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.

The big question is: how can i delegate PHP to check if a resources is an HTTP 200 or an HTTP 304 ?

Upvotes: 0

Views: 1513

Answers (1)

Jonathan Amend
Jonathan Amend

Reputation: 12815

Here's some sample code for managing browser caching for a page served with PHP. You'll need to determine a timestamp $myContentTimestamp that indicates the last modified time of the content on your page.

// 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);
}

Upvotes: 2

Related Questions