Cache headers for dynamic css (generated via PHP)

My CSS file is a PHP file that is served with the text/css content type, so I can use PHP variables in this file. style.php as follows:

 <?php header('Content-Type: text/css'); $bgColor = '#000'; ?> body { background:<?php print $bgColor; ?>; } 

It works as expected, but I'm a little worried if the browser caches a dynamically generated css file.

When viewing requests in firebug, it seems to me that the browser style.php again every time I reload the page.

I already tried to add these cache headers:

 header('Cache-control: must-revalidate'); header('Expires: ' . gmdate('D, d MYH:i:s', time() + 60 * 60 * 24) . ' GMT'); 

But no luck. A file is downloaded every time the page loads. What are the appropriate headers to make the browser cache the file for a certain amount of time?

+7
css php caching dynamic header
source share
2 answers

If you want the file to be cached by browsers, you must configure the Cache-control public header:

 header('Cache-control: public'); 

must-revalidate means that the browser will check if the file that your PHP script will call has been updated.

+2
source share

This code solves your problem.

It checks the "last modified" variable and assigns an eTag to the file. If the eTag is modified (or the file is modified), the file is displayed. Otherwise, there is a 304 HTTP error indicating that the page has not been modified.

eTag is actually what you are looking for.

the code:

 <?php // Custom variables $variables = array('#CCC','#800'); // from db // CSS Content header('Content-type: text/css'); // Last Modified $lastModified = filemtime(__FILE__); // Get a unique hash of this file (etag) $etagFile = md5_file(__FILE__); // Get the HTTP_IF_MODIFIED_SINCE header if set $ifModifiedSince = (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) ? $_SERVER['HTTP_IF_MODIFIED_SINCE'] : false); // Get the HTTP_IF_NONE_MATCH header if set (etag: unique file hash) $etagHeader = (isset($_SERVER['HTTP_IF_NONE_MATCH']) ? trim($_SERVER['HTTP_IF_NONE_MATCH']) : false); // Set last-modified header header("Last-Modified: ".gmdate("D, d MYH:i:s", $lastModified)." GMT"); // Set etag-header header("Etag: $etagFile"); // Make sure caching is turned on header('Cache-Control: public'); // Check if page has changed. If not, send 304 and exit if(@strtotime($ifModifiedSince) == $lastModified || $etagHeader == $etagFile){ header("HTTP/1.1 304 Not Modified"); exit; } ?> body {background: <?php echo $variables[0]; ?>;} 
+1
source share

All Articles