2011-09-04 99 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