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

2
  • 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) Sep 6, 2011 at 18:11
  • I already do that, edited post.
    – ddinchev
    Sep 6, 2011 at 18:20

3 Answers 3

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.

3
  • Can you explain why this answers the question?
    – Todd
    Aug 18, 2017 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, 2017 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... Dec 27, 2018 at 1:44
7

Make sure you also add public as so:

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

Read this also, is very helpful.

2
  • 2
    The correct one is: header('Pragma: public'); header('Cache-Control: max-age=86400'); Buy you gave me the idea
    – ddinchev
    Sep 6, 2011 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 6, 2011 at 18:43
2

An Expires header should help.

header('Expires: '. gmdate('D, d M Y H:i:s \G\M\T', time() + 86400));
0

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge that you have read and understand our privacy policy and code of conduct.

Not the answer you're looking for? Browse other questions tagged or ask your own question.