在一个随机生成图像的PHP脚本中,为什么在一个页面上多次调用它总是生成相同的图像


In a PHP script that produces an image at random, why does calling it multiple times on a page always produce the same image?

我正在制作一个网页April愚人节恶作剧,页面上的所有图像都被从图像中随机挑选的图像所取代。我有一个php脚本,可以随机选择图像并发送图像:

<?
$files = array('pacman', 'blinky', 'cherry', 'clyde', 'inky', 'pinky'); 
$name = $files[array_rand($files)] . '.png';
header("Content-Type: image/png");
header("Content-Length: ".filesize($name));
readfile($name);
?>

这很好,每次访问时都会返回一个随机图像。

第2步是用脚本替换所有图像源属性,我通过包含一个javascript文件来完成这一操作,该文件的内容看起来像:

$(document).ready(function(){
    $('img').attr('src', 'april.php')
});

这也是有效的,除了一个问题:它似乎只选择一个随机图像一次。也就是说,页面上的所有图像都将是相同的图像。如果我刷新,它将是一个随机选择的图像,但在下一次刷新之前,页面上的所有内容都将是相同的图像。

我猜浏览器是第一次缓存它,实际上并没有调用php脚本,但我不知道如何禁用或运行它。

那么,为什么会发生这种情况,我该如何解决呢?

PHP每次都会生成一个随机图像,但浏览器会将该图像保存在缓存中并加载。

将此添加到您的PHP代码中:

  header("Cache-Control: no-cache, must-revalidate");

但是,在您的情况下,由于图像已经加载,您必须首先硬刷新页面CTRL+F5

另一种方法是向URL添加get请求。

  $('img').attr('src', 'april.php?t=' + Math.floor(Math.random() * 60000) + 1);

对于多张图片:(感谢@Francesco de Guytenaere发现它)

  $('img').each(function(){ $(this).attr('src', 'april.php?t=' + Math.floor(Math.random() * 60000) + 1); });

然而,这会改变整个页面上的每个图像,也许你想使用选择器,只选择具有特定data-tag的图像

  <img src="image/to/background" />
  <img src="" data-cache="no" />
  <img src="" data-cache="no" />
  $(document).ready(function(){
    $("img[data-cache='no']").each(f.....
  });