首页 > 解决方案 > 如何在PHP中刷新页面时显示最后上传的图像

问题描述

我有一个应用程序,它使用 file_get_contents 和 file_put_contents 方法从动态图像源生成图像。创建图像后,图像将上传到我服务器上的目录。我面临的问题是每次生成图像并刷新页面时都会看到旧图像出现。当我清除缓存时,它会显示新图像。

我该如何解决这个问题?

<?php
$imagename = "img".$id.".png";
$host = $_SERVER['DOCUMENT_ROOT'];

$path     = $host.'/url/path/img/'.$imagename;
if(file_exists($path)) {
    //echo 'File already exists in that directory';
    unlink($path);
    $filehandler =  file_get_contents($imgurl);
    file_put_contents($path, $filehandler); 
}
else {
    $filehandler =  file_get_contents($imgurl);
    file_put_contents($path, $filehandler);
}

标签: php

解决方案


最好将版本用作所有图像、js 和 css 文件的查询参数。使用时间戳不会那么好,因为如果图像未更新,它将不会从缓存中显示。所以为了避免额外的开销使用版本的图像

也就是说,最初

<img src="image.png?v1" />

直到现在发生下一次更新,这应该是 URL

一旦更新,它应该更改为

<img src="image.png?v2" />

推荐阅读