A Better Image Rotator

The Hiveware Image Rotator, shared by Mr Zeldman, does one thing and does it fairly well: it shows a random image on each reload. However, the approach the script takes is slightly flawed, and could be improved as detailed below.

My first issue with the script is that it is really only set up to handle two types of files, GIF and JPEG, and then only with the file extensions of .gif or .jpg, so something like .jpeg (fairly common) would not be included. Not to mention the noble PNG is left out entirely. Fixing this, however, leads us to a more fundamental problem: the images are served through the script. This means that the script has to handle the content-type header, something that is messy to do. A better method, I propose, is for the script to merely serve a temporary redirect header, which sends the browser with a minimum of overhead to the actual location of the file, which has a number of tangential benefits including that it allows the image itself to be cached properly, either by a caching server or the browser itself, and it delegates content negotiation and such to the web server, which is most likely infinitely better at it.

So now what we have a script which reads files in a directory, grabs the ones with a user defined set of file extensions, and sends a simple Location header to whichever file is randomly chosen. The complication now that the location of the image is now important in terms of the web server document root. One bonus of Dan Benjamin’s method is you can use images outside of the web root, though I don’t know why anyone would want to do this. The script could ask for two variables to be defined, the absolute path to the images and the path to the images through the web server, but I would like for this to be as ridiculously easy to setup as possible. Another option would be to subtract the $DOCUMENT_ROOT variable from the absolute path given and use that, but that would require people to know the absolute path of the directory they’re using, and like I said I’d like this to be easy as humanly possible. The best solution is to use a relative path; if the users enters nothing it’s assumed that the images are in the same directory as the script but if they aren’t the path can be entered in a relative manner, like “images/random” or “../rand-img”. Easy peasy.

Finally, instead of the plain rand() we’ll use mt_rand, which is about four times faster and slightly more random. What do you get? The Photo Matt Random Image Script. I’ve tested it thoroughly, but if you have any problems don’t hesitate to let me know. It’s just standard HTTP though so I don’t foresee any trouble. Something neat about this is that with the code we just wrote, you can also serve random anything—from zip files to MP3s—just by changing the extension line. Enjoy! Here’s an example of it in action, you should recognize some of the images as the delightful graphics Jeffrey has been putting up, the rest are snips of photographs I haven’t uploaded yet.

A Random Image

28 thoughts on “A Better Image Rotator

  1. Nice work. 🙂

    But wouldn’t it be nice to be able to set a unique alternate text for each image, as well as use images of different sizes (dimensions)? For my part, i just get a random img tag from an array of img tags, each one having its own dimension and alternate text.

  2. Here’s a scripting challenge for Matt or other. An image randomizer that has a timer for image display AND with each image a link back to the image’s web site (and _blank) for a new browser window. The application would be great for randomly displaying logos of participating sponsors or partners. The Java based image scrollers (like Coffee Cup’s Applet Headline Factory) have this feature, but are trapped in a linear display mode.
    If anyone knows of this script already existing.. please use my email to fill me in on it’s whereabouts.
    Thanks – Stan

  3. I tried using your script for calling different css background images through an imported stylesheet — and this method works when browsing with ie6 — when using Mozilla Firefox the browser seems to cache the path to the image thus showing always the same image — I havn’t tried any other browsers.

    cheers Gerrit

  4. I assume I could use this image rotator code to show a wide variety of headers randomly for my blog? I think this could be pretty cool. I’m glad to be learning about this possibility and associated coding.

  5. I’m trying to set up a random-loading image for a header background and I’m running into the Mozilla/Firefox caching issue where it seems to get ‘stuck’ and only displays the same image over and over. Is there a fix for this?

  6. I know this is 5 1/2 months later, but this might be fixed by clearing your cache. My image rotator wouldn’t stop showing the same header (in Mozilla and Netscape) until I did that.

    Better late than never?

  7. Firefox has some unique web caching features that are designed to speed up the browsing process. With scripts like this, Firefox can appear to have its share of issues.

    To quote an article released on the Scot Finnie Newsletter page – he addresses this issue as follows:

    There’s only one about:config-based tweak that I’m currently recommending (although I expect to add others in the near future). This recommendation really only applies to people who have fast Internet connections or those who are Webmasters, news junkies, possibly online gaming, anything where it’s mandatory that clicking the Refresh button always shows you the very latest information on that Web page. If that describes the way you need or want to work, you can configure Firefox to work the same way Internet Explorer’s check for website updates on “Every visit to the page.”

    To make this change, find this entry in about:config:


    The default setting is represented by the numeral 3, and corresponds to “when appropriate/automatically.” To change it, simply double-click the browser.cache.check_doc_frequency entry. A small dialog box will open. Type the numeral 1 to change it to “Each Time” and press OK. Here’s a description of the available options for this particular setting:

    0 = Once per session
    1 = Each time
    2 = Never
    3 = When appropriate/automatically


    The following is a workaround for the Firefox caching problem. Images are reloaded with every click (up to 100 different images). In the code shown below simply replace the [] brackets with tags

    Two steps to firefox heaven:
    1. insert this somewhere above where the rotation script is called:
    [?PHP srand((double)microtime()*1000000); ?]
    2. change the url of your rotate.php to this:
    rotate.php?image=[?PHP echo rand(0,100); ?]

    If you really need more than 100 randomised images change the 100 figure.


  9. I work often with sites/pages that use server-side caching, so PhilMills’ solution above doesn’t work (as the random number that’s generated would get cached also!). In the past I’ve instead implemented the same approach, but in Javascript. I’m not sure if I can paste code here, so I’ll just explain how:

    1) Output your IMG tag as normal, or using the solution immediately above (this will ensure it still works if JavaScript is disabled)
    2) Give the IMG tag an HTML ID (such as ‘randimage’)
    3) Immediately after the IMG tag include some inline javascript ( using “script” tags … also within a CDATA comment if doctype is xhtml): “document.getElementById(‘randimage’).src = document.getElementById(‘randimage’).src + ‘?rand=’ + (Math.rand() * 10000000);”

    Hope this helps someone.

  10. I know this post is a few years old, but I just wanted to say that I have looked at every image-related plugin on the wordpress website and none did the job this does. It is very simple and I was able to create three instances of the random image side by side. It looks great and I am so grateful because I know not a thing about php! Thanks!

  11. Matt, thanks for the php script – it’s great!

    @ Dave A – the combination of Phil’s FF workaround and your javascript has done the trick for me. Thanks.

    But – Math.rand() should be Math.random(). Math.rand() is not a function).

  12. Hivelogic’s A Better Image Rotator script broke again on Dreamhost, so thank you very much for having this here. Got it installed in minutes.

    FWIW I
    I don’t get Dreamhost is always doing, but I’m always having to re-load the Hivelogic files.

    I didn’t have to do any Firefox/javascript crap.

    I do like the Hivelogic script better than Matt’s because it allows each image to have a contextually proper alt and title and a custom link for each image, too.


    P.S. I shall now check out if there is indeed something else out there with alts, titles and urls.

  13. Thanks for the great script. I made a minor mod to select a folder at random as well. We have various events with lots of images for each. The images are in separate folders:

    $folders[1] = ‘../feeFolder/images/’;
    $folders[2] = ‘../fiFolder/images/’;
    $folders[3] = ‘../foFolder/images/’;
    $folders[4] = ‘../completelyDifferentFolder/’;

    $folderCount = count($folders);
    $folderNumber = mt_rand(1, $folderCount);
    $folder = $folders[$folderNumber];

  14. Well some scripts are like good red wine. The older the better 🙂 Almost 6 years since this post was made and I stumbled upon this coz simply, it’s a reference when it comes to simple image rotation. Good job!
    Got it working in less then 1minute.

  15. After so many years (Wow! Almost 10 years!), I’m still thinking on how to include a link to each image. Are you there Matt?

Leave a Reply to FireWolfCancel reply