Chris Chris - 2 years ago 69
jQuery Question

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

I am working on a web page April fools prank where all images on the page are replaced with an image picked at random from a selection of images. I have a php script that picks the image at random and sends the image:

$files = array('pacman', 'blinky', 'cherry', 'clyde', 'inky', 'pinky');

$name = $files[array_rand($files)] . '.png';

header("Content-Type: image/png");
header("Content-Length: ".filesize($name));


This works fine, returning a random image each time it is visited.

Step 2 was replacing all image source attributes with the script, which I do by including a javascript file that has contents that looks like:

$('img').attr('src', 'april.php')

This also works, except for one catch: it seems to only pick a random image once. That is to say, all images on the page will be the same image. If I refresh, it will be a randomly selected image, but it will be the same image for everything on the page until the next refresh.

I would guess that the browsers are caching it the first time and are not actually calling the php script, but I'm not sure how to go about disabling, or working aorund it.

So, why does this happen, and how would I go about fixing it?

Answer Source

PHP will generate a random image every time, however your browser keeps that image in cache and loads that instead.

Add this to your PHP code:

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

However, in your case since the image is already loaded you must first hard-refresh the page. CRTL+F5

An alternative method is adding a get request to the URL.

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

For multiple images: (Credits to @Francesco de Guytenaere for spotting it)

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

However this will change every image on the entire page, maybe you want to use a selector and only pick images that have a specific data-tag like so.

  <img src="image/to/background" />
  <img src="" data-cache="no" />
  <img src="" data-cache="no" />

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download