Reputation: 5778
I am generating some images using a PHP script.
I want to cache the images, so the browser doesn't have to load them each time.
I have added these headers:
'max-age' => 3600
'Etag' => md5($image->getSlug())
'last-modified' => $image->getUpdatedAt()
'Vary' => 'Accept-Encoding'
'content-length' => (size of the image)
'Content-type' => 'image/jpeg'
but the image is not cached, and it is loaded every time by the browser.
The response headers look like these (using Firebug):
Date Sun, 04 Sep 2011 00:25:45 GMT
Server Apache/2.2.16 (Debian)
X-Powered-By PHP/5.3.3-7+squeeze1
Cache-Control max-age=3600, private
Etag "9280c6c672c6535c13b7481972f9ac39"
Last-Modified Sat, 27 Aug 2011 01:36:24 GMT
Vary Accept-Encoding
Content-Length 26231
Connection close
Content-Type image/jpeg
Does anyone have any idea what is wrong here?
Upvotes: 2
Views: 1158
Reputation: 2049
One way you can force an image to be cached is to set the Last-Modified
tag to the date and time that the image you want to use was created. For example:
<?php
error_reporting(0); //disable error reporting as it will corrupt the image
session_start(); //start a php session
$date = date(DATE_RFC822);
//some code to connect to a mysql database
$query = mysqli_query($link, "SELECT * FROM images WHERE sessionid='$sessionid'");
if ($query and mysqli_num_rows($query) == 1) { //if mysql returned one row
$row = mysqli_fetch_array($query); //get the row as an array
$date = $row["date"]; //set the date to the one in the database
} else { //if the user has never seen the image before
mysqli_query($link, "INSERT INTO images SET sessionid='$sessionid', date='$date'"); //put the session id and date into the database for later use
}
header("Last-Modified: $date");
//some code that would generate and send the image
Don't forget to create a database (in any database program) that contains a table called images
with sessionid
, which should be the primary key, and date
. Both should be strings.
Upvotes: 2
Reputation: 15361
You need to calculate and add an Expires: header. For example:
Expires: Fri, 30 Oct 2011 14:19:41 GMT
Upvotes: 0