Skip to content Skip to sidebar Skip to footer

How Are Images Cached When Loaded Via Php Script

I have a php script acting as a random image generator. The script queries the database for the user's images, and returns the path to one, at random. Here is the portion of the c

Solution 1:

Why not have getRandomImage be a PHP function, which returns a path to the image. You can render the page out with the random image paths already filled in.

<imgsrc="<?echo getRandomImage() ?>">

Then you can actually serve your images with real cache headers, and your bandwidth wont be getting hammered so hard.

Do this on the server side while the page is rendering, not after. Doing it after is more work and, as you are finding out, is more complicated too.

Solution 2:

The caching has nothing to do with the PHP script; it happens at the browser.

Try adding this to the script, to try and force the browser to not cache it (from PHP website):

header("Cache-Control: no-cache, must-revalidate");  // HTTP/1.1header("Expires: Sat, 26 Jul 1997 05:00:00 GMT");    // Date in the past

Solution 3:

Just make randomImage.php redirect to a seeded version if it isn't present.

if (!isset($_REQUEST['seed']))
{
      header("Location: randomImage.php?seed="+rand());
      exit;
}

Feel free to make the randomizer more random.

Solution 4:

Browsers expect that the same will always represent the same image. And I think that even headers that force no caching at all wont even stop the browser from reusing the image on the same page. So a image source that is different each time you call it is pretty counter intuitive.

Cache busting is probably your best bet. That means like you random hack there, although there is ways to do it better. For instance, appending an increasing integer to the current time. This way you never duplicate urls.

var count = 0;
var now = newDate().getTime();
imgs[0].src = "/database/getRandomImage.php?" + (count++) + now;
imgs[1].src = "/database/getRandomImage.php?" + (count++) + now;
imgs[2].src = "/database/getRandomImage.php?" + (count++) + now;

But really, you may want to rethink your strategy here, because it sounds a little fishy.

Post a Comment for "How Are Images Cached When Loaded Via Php Script"