I have a php dynamically generated image which I need to write to file to call later. My problem is that I need this image to have appropriate expiration headers included in it. There are a massive number of these and their headers vary individually file-by-file making .htaccess controls not an option.
I can write expiration headers if I’m outputting the image directly to the browser with this:
header(“Content-Type: image/jpeg”);
header(‘Expires: “‘ . gmdate(“D, d M Y H:i:s”, $expirationDate) . ‘”‘);
imagepng($image, NULL);
Or I can write the image to a file to be used later with this:
imagepng($image, $filepath)
But I can’t for the life of me figure out how to combine those two and write the image to a file while including its expiration headers. How would you go about writing an image file with an expires header?
I think your best bet it to server the file just as you are, something like:
Sure you’re using php to serve a static file, but the expire header is going to limit repeat requests.
Update: Since
$imageis a generated file, on the first request generate and save the image, then output it. On additional requests, just output the already generated image. Essentially theexpireheaders are controlling the browser’s cache, while you need to implement some kind of caching on the server to avoid generating the same output multiple times.So you’re looking at two different kinds of caching. You can do them in the same script, with a combination of two scripts – really however you want.
Unless you can set a standard expire header with apache (which you say you can’t, since it varies), I believe this is your best (if not only) choice.
Of course there is the convoluted and complex way:
Or something like that. I’d just serve them all up using php.
Update: Or use
mod_asisfrom VolkerK’s great answer.