25

I have images (PNG) that are generated dynamically and will be embedded in websites and forums. When an image gets posted on a very busy page, there are a lot many connections to service for something that doesn't change often. I want to tell the browser for how long to cache it.

So what headers do I need? Currently, I have:

Cache-Control: max-age=86400
Content-Type: image/png

It seems that the browser is not caching the image (it is about 20-30kb). What else would be necessary?

Edit: This is an example image, I already have an URL with .png extension: https://images.carspending.com/sigimg/5734/user/honda-accord-2-4i-executive-tourer_medium.png

ddinchev
  • 33,683
  • 28
  • 88
  • 133
  • 1
    It would certainly make it easier to the browser if you had an URL that actually looks like an image (eg: `http://www.example.com/images/myimage.png` rather than `http://www.example.com/my_script.php?image=93895`) – NullUserException Sep 06 '11 at 18:11
  • I already do that, edited post. – ddinchev Sep 06 '11 at 18:20

3 Answers3

37

The final thing that worked was:

header('Pragma: public');
header('Cache-Control: max-age=86400');
header('Expires: '. gmdate('D, d M Y H:i:s \G\M\T', time() + 86400));
header('Content-Type: image/png');

Now the browser does not make requests for the image when loading a page with embeded one.

ddinchev
  • 33,683
  • 28
  • 88
  • 133
  • Can you explain why this answers the question? – Todd Aug 18 '17 at 14:29
  • At the time it was answered (6 years ago) it did solve the problem. If a png resource with all of these headers was loaded on an external page, it would be properly cached. Isn't it working for you? – ddinchev Aug 21 '17 at 13:38
  • It does not work for me, I'm on Google Chrome 71 and these headers only work if the `png` is in the browser session, once Crome restarted it loads images from the internet again. I also tried `Cache-control: immutable, public, max-age..., stale-while-revalidate...`, `access-control-allow-origin`, `timing-allow-origin`, nothing seems to work... – Yevgeniy Afanasyev Dec 27 '18 at 01:44
7

Make sure you also add public as so:

header('Cache-Control: max-age=86400, public');

Read this also, is very helpful.

jedierikb
  • 12,752
  • 22
  • 95
  • 166
Icarus
  • 63,293
  • 14
  • 100
  • 115
  • 2
    The correct one is: header('Pragma: public'); header('Cache-Control: max-age=86400'); Buy you gave me the idea – ddinchev Sep 06 '11 at 18:38
  • @Veseliq: I'm glad. I'm no PHP developer so I took a WILD guess ;) And good that you set the Expires date in GMT format; otherwise, it would not have worked either. – Icarus Sep 06 '11 at 18:43
2

An Expires header should help.

header('Expires: '. gmdate('D, d M Y H:i:s \G\M\T', time() + 86400));
ceejayoz
  • 176,543
  • 40
  • 303
  • 368