Last Updated: February 25, 2016
· euantor

Adding client-side cache headers to images created using PHP's GD

We all know that caching is a good idea whenever possible. Creating images using PHP's GD Library is no expception either (unless, of course, you don't want the images to be cached as in cases such as captcha type images).

Luckily, it's very easy to set up both server side and client side caching. To add your caching headers for client side caching, it's as simple as the following (note that we're assuming we wish to cache the file for 30 minutes before a new version must be fetched):

header("Content-type: image/png");
header('Last-Modified: '.gmdate('r', time()));
header('Expires: '.gmdate('r', time() + 1800));

You really should be doing this kind of thing whenever you possibly can to save on resources and reduce bandwidth usage. It also means the images will render more quickly for your users which is always a plus.

Say Thanks