Handling If-modified-since header in a PHP-script

This is definitely possible in PHP!

When the browser checks if there were modifications, it sends an If-Modified-Since header; in PHP this value would be set inside $_SERVER['HTTP_IF_MODIFIED_SINCE'].

To decode the date/time value (encoded using rfc822 I believe), you can just use strtotime(), so:

if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) && 
    strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= filemtime($localFileName))
{
    header('HTTP/1.0 304 Not Modified');
    exit;
}

Explanation: if the If-Modified-Since header is sent by the browser AND the date/time is at least the modified date of the file you’re serving, you write the “304 Not Modified” header and stop.

Otherwise, the script continues as per normal.

Leave a Comment