defacto
defacto

Reputation: 359

Cache images/js/css never HTML content

I'm looking for a PHP header() way to cache images but never html content of php output. For now, I am using theses lines on my .htaccess file:

<filesMatch "\.(ico|gif|jpg|jpeg|png|flv|avi|mov|mp4|mpeg|mpg|mp3|pdf|doc|css|js|html|bmp|js|css)$">
  Header set Cache-Control "max-age=86400000"
</filesMatch>

And I don't do any header.

I would prefer to send headers like these at the top of my php files, so I tried these:

header("Expires: Mon, 26 Jul 1997 05:00:00 GMT");
header("Last-Modified: " . gmdate("D, d M Y H:i:s") . " GMT");
header("Cache-Control: no-cache");
header("Cache-Control: post-check=0, pre-check=0");
header("Pragma: no-cache");

But with these header functions, images are not cached in browsers if I close the browser and go back to the site. Whhat do I have to send to browsers to cache images but never HTML content ?

EDIT: Sorry but I checked again and I feel like these header functions are enough to make the browser cache images and not the html content.

Upvotes: 1

Views: 1323

Answers (1)

stackuser10210
stackuser10210

Reputation: 352

one option may be to load your images from a dedicated php file:

header('Content-Type: image/png');
header('Cache-control: private');
$img = imagecreatefrompng("example.png");
imagepng($img);
imagedestroy($img);

to save having a separate php file for each, you could pass the filename on the uri. eg, the path to the image would then be image.php?filename=example.png, using $_GET['filename'] in the php script.

*im not sure if Cache-control: private would really be necessary, but ive included it as hopefully helpful hint.

Upvotes: 0

Related Questions