Friday, April 9, 2010

for your PHP library: send_cache_control_headers()

Good caching is a really important part of getting the most out of your server(s) while providing visitors with the best experience. While I am not going to discuss best practices for caching now, I will share a very simple, but helpful PHP function that I use on svidgen.com.

And here it is:

function send_cache_control_headers($t '+1 year') {
    
// set cache-control header
    
$cc_header strtotime($t0);
    
header("Cache-Control: max-age={$cc_header}");

    
// set expires header
    
$exp_header gmdate('D, d M Y H:i:s \G\M\T'strtotime($t));
    
header("Expires: {$exp_header}");

    
// set Pragma header to NOT "no-cache" if necessary
    
$current_headers headers_list();
    foreach (
$current_headers as $header) {
        if (
$header == 'Pragma: no-cache') {
            
header('Pragma: cache');
            break;
        }
    }

// send_cache_control_headers()



See? It's really simple. But, for a site like Svidgen, where nearly everything is served up through single "driver" script, this is a very handy function to have available. I include it in the driver, and it makes setting the appropriate cache-control headers on any page or template a trivial one-liner. It's the little added convenience I needed to get the right caching headers "installed" on all my scripts and stylesheets.

It's a fairly trivial routine. But, it's nice to not have to think about it, isn't it?

1 comment: