缓存动态生成的图像

时间:2011-09-04 00:30:38

标签: php browser-cache

我使用PHP脚本生成一些图像 我想缓存图像,因此浏览器不必每次都加载它们。 我添加了这些标题:

'max-age' => 3600
'Etag' => md5($image->getSlug())
'last-modified' => $image->getUpdatedAt()
'Vary' => 'Accept-Encoding'
'content-length' => (size of the image)
'Content-type' => 'image/jpeg'

但图像未缓存,每次都由浏览器加载。

响应头看起来像这些(使用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

有没有人知道这里有什么问题?

2 个答案:

答案 0 :(得分:2)

您可以强制缓存图像的一种方法是将Last-Modified标记设置为您要创建的图像的日期和时间。例如:

<?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

不要忘记创建一个数据库(在任何数据库程序中),该数据库包含一个名为images的{​​{1}}表,该表应该是主键,sessionid。两者都应该是字符串。

答案 1 :(得分:0)

您需要计算并添加Expires:标头。例如:

Expires: Fri, 30 Oct 2011 14:19:41 GMT
相关问题