Cache

Created 2011 March 27. Updated 2011 March 27.

CSS and PHP Link Drop

Transparent Caching of CSS or JS

Although the Caching css, js etc. by filip above works I wanted to cache in a way that was as transparent as serving a regular CSS file, the following is what I came up with:

// Tell the browser this is a CSS file
header("Content-type: text/css");

// Get the last modified date of the file and tell the browser
$gmLastModified = gmdate("D, d M Y H:i:s", filemtime(__FILE__))." GMT";
header("Last-Modified: ".$gmLastModified);

// Get the date stored in a If-Modified-Since request, if it exists
$ifModifiedSince = isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : false;

// Compare the If-Modified-Since request with the last modified date of the file and if the same return a 304, which
// ensures the browser gets the file from browser cache
if ($ifModifiedSince == $gmLastModified) {
    header("HTTP/1.1 304 Not Modified");
    exit;
}

For JS files change text/css for text/javascript