Php 文件存在 return 相同的图像

Php file exists return same image

这就是我正在做的检查文件是否存在并在页面中回显,但是页面显示旧图像,即使它已经被另一个图像替换它只显示旧图像,但新图像在那里并且旧的已被同名的新图像取代。

<?php 

$dir = 'up/images/'.$_SESSION ['username'].'.png';

if (file_exists($dir)) {
    //echo "ok";
  echo '<img  src="up/images/'.$_SESSION['username'].'.png" class="img-responsive img-thumbnail" width="200px;" height="200px;">'; 

} else {
   //not found 

  echo '<img  src="img/user-icon-yellow.png" class="img-responsive img-thumbnail" width="200px;" height="200px;">'; 
}


?>

好像是缓存问题什么的。

这是缓存。尝试在 Google Chrome 上按 CTRL + F5 或直接进入“设置”并删除缓存文件。

您始终可以安装 Google Chrome 扩展程序,它可以在每次刷新时删除特定网站的缓存文件。

消除缓存破坏的一个好方法是将版本字符串添加到您的图像路径中。例如:

$image = basename($_SESSION['username']) . ".png";
$image = realpath("/path/to/$image");
echo '<img src="up/images/'.$_SESSION['username'].'.png?v='.filemtime($image).'" [...]>';

这是假设您的 HTML 页面没有被缓存,如果它们被缓存,那么您将需要发送额外的 headers 来破坏缓存。这取决于环境,但对于 Apache 之类的东西,您可以执行以下操作:

 Header set Cache-Control "max-age=0, no-cache, no-store, must-revalidate"
 Header set Pragma "no-cache"
 Header set Expires "Wed, 11 Jan 1984 05:00:00 GMT"

或者,您可以使用 PHP 的 header() 函数来设置 headers:

 header("Cache-Control: max-age=0, no-cache, no-store, must-revalidate");
 header("Pragma: no-cache");
 header("Expires: Wed, 11 Jan 1984 05:00:00 GMT");

确保您确实更换了图片。并且 图片在您刷新页面之前不会改变。 PHP不是动态语言(结果(新图像)不会在您更改它的那一刻出现)。
当您替换图像时,请执行此操作以刷新页面:

header("Refresh:0"); //Refreshes the page after 0 second (immediately)

您也可以尝试使用:

header('Location: '. $_SERVER['PHP_SELF']); //It will redirect the page to the same page and probably clear the cache