Cache php-generated image until it changes

☆樱花仙子☆ 提交于 2019-12-12 17:55:51

问题


I apologize in advance for my lack of knowledge on this subject; I've looked at lots of other posts but can't get any of their solutions to work for me.

Anyway, I'm using a dynamic displayimage.php file to show users' profile pictures on a site I'm working on. The page takes an id parameter, and pulls the image filename from a mysql database. Here's the (abbreviated) code:

$id = mysql_real_escape_string($_GET[id]);

$table = "images_user";
$idname = "userid";
$uploaddir = "/home/username/uploads/images/user/"; //outside web root

$select = mysql_query("SELECT * FROM $table WHERE $idname = '$id' LIMIT 1");

if(mysql_num_rows($select) > 0) {
  $file = mysql_fetch_assoc($select);

  header("Content-Type: $file[mimetype]");
  readfile($uploaddir.$file[name]);
}

Currently, because it's generated from a php file, the image is not being cached, which really slows the site down. So I add this:

header("Cache-Control: private, max-age=10800, pre-check=10800");
header("Pragma: private");
header("Expires: " . date(DATE_RFC822,strtotime(" 2 day")));

Which solves the problem, great! Now the images are cached, and load super quickly.

However, users have the ability to change their profile pictures. When this happens, I save their uploaded picture, delete the old one, and update the database entry to point to the new picture. But now, because the old picture is still cached, they don't see the update unless they manually F5 the page.

How can I get it to cache the picture, but force a 're-cache' when the picture has been changed?


回答1:


after they update the picture, add an extra parameter to the url you access to show the image, which here is `displayimage.php'. Most commonly this would be a timestamp.

Like in normal case, you would access displayimage.php?id=123123

and after updating the profile pic, to refresh the image, you will need to access displayimage.php?id=123123&time=1000121110. The changing time parameter would force an image reload from the page everytime the user updates the image.




回答2:


Currently your url to the script looks something like:

displayimage.php?id=X

What you need to do is add a versioning number for each user that gets incremented every time the user updates his profile picture:

displayimage.php?id=X&v=Y

The versioning number could be stored in the database as well.

The versioning number could also be the last modified time on the image file uploaded which avoids using another table field and incrementing code:

displayimage.php?id=X&v=TIME


来源:https://stackoverflow.com/questions/11400184/cache-php-generated-image-until-it-changes

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!