I have a PHP script which is called with an ?img= parameter.
The value for that parameter is an (urlencoded) URL of an image.
My script chec
I recently had to use this feature (serving image via PHP) in order to make images visible only for registered users. Jack's code was helpful, but I had to do a few hacks for it to work perfectly. Thought I should share this one.
if (isset($_SERVER['HTTP_IF_MODIFIED_SINCE']) &&
strtotime($_SERVER['HTTP_IF_MODIFIED_SINCE']) >= filemtime($path_to_image))
{
header('HTTP/1.0 304 Not Modified');
header("Cache-Control: max-age=12096000, public");
header("Expires: Sat, 26 Jul 2015 05:00:00 GMT");
header("Pragma: cache");
exit;
}else{
header("Content-type: image/jpeg");
header("Cache-Control: max-age=12096000, public");
header("Expires: Sat, 26 Jul 2015 05:00:00 GMT");
header("Pragma: cache");
echo file_get_contents($path_to_image);
}
In short, the script returns Not Modified if it's a browser request HTTP_IF_MODIFIED_SINCE
. Otherwise, the image is served with appropriate headers and expiry dates.
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.