2011-09-04 98 views
2

我正在使用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 

没有人有任何的想法有什么不对吗?

+0

你有没有想过这个?我有同样的问题.. – jbsmoove

回答

0

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

Expires: Fri, 30 Oct 2011 14:19:41 GMT 
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 

不要忘记创建一个数据库(任何数据库程序),包含的表中调用imagessessionid,这应该是主键,date。两者都应该是字符串。

+0

如果你看我的原始文章,你会看到我已包括最后修改。 –

+0

@Ako啊,是的,对不起,我的坏。那么,除了可能使用“file_put_contents”保存图像的内容,然后在显示它的页面上使用图像文件名称之外,我无法考虑其他任何可以完成的操作。 – kirb