【问题标题】:Cache a dynamically generated image缓存动态生成的图像
【发布时间】:2011-09-04 00:30:37
【问题描述】:

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

有人知道这里出了什么问题吗?

【问题讨论】:

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

标签: php browser-cache


【解决方案1】:

强制缓存图像的一种方法是将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 的表和sessionid(应该是主键)和date。两者都应该是字符串。

【讨论】:

  • 如果您查看我的原始帖子,您会发现我已包含 Last-modified。
  • @Ako 啊,是的,对不起,我的错。好吧,除了可能使用“file_put_contents”保存图像的内容,然后在显示它的页面上使用图像文件名之外,我想不出其他任何方法。
【解决方案2】:

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

Expires: Fri, 30 Oct 2011 14:19:41 GMT

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-04-01
    • 1970-01-01
    • 2023-03-28
    • 2017-07-08
    • 1970-01-01
    • 2019-09-06
    相关资源
    最近更新 更多