Ali
Ali

Reputation: 267287

How to cache an image being served through PHP?

I'm setting the background-image of my website to a url on the server, which is a php script and which serves an image as its output. Here is the code for it:

   //$mime is usually image/jpeg, etc
   header("Content-type: $mime");
   $image = readfile($image);
   imagejpeg($image);

The issue is, each time I load my page, the image seems to be loaded again rather than being cached. Is there anything I can do about that, e.g to send a header to cache the image?

Upvotes: 1

Views: 1295

Answers (3)

Mihai Iorga
Mihai Iorga

Reputation: 39724

I always get best results using the ETag (a md5 hash) and Last-Modified (a past date, usually when the file was created).

for your code it will be like this:

$etag = md5_file($image);
$lastModified = gmdate('D, d M Y H:i:s', filemtime($image)) . ' GMT';


header("Content-type: $mime");
header("ETag: \"{$etag}\"");
header("Last-Modified: $lastModified");
header('Expires: ' . gmdate("D, d M Y H:i:s", ((60*60*24*45)+strtotime($lastModified)))); // add 45 days expire

$image = readfile($image);
imagejpeg($image);

Upvotes: 5

Jocelyn
Jocelyn

Reputation: 11413

I suggest adding a header to tell the date the image file was last modified:

 header("Last-Modified: " . gmdate("D, d M Y H:i:s", filemtime($image)) . " GMT");
 header("Content-type: $mime");
 $image = readfile($image);
 imagejpeg($image);

This way the browser will be able to cache the image.

Upvotes: 1

Razvan
Razvan

Reputation: 10101

Use the last-modified header field and set it to a date in the past all the time.

This way the browser will receive a "not modified" reply from your server and will use the cached version of the image.

Upvotes: 1

Related Questions