Random Image Rotation

by Dan Benjamin

58 Reader Comments

Back to the Article
  1. Nice article :)

    If anyone is interested in an ASP version:

    Demo : http://www.duelcom.com/malani/db/img/

    http://www.duelcom.com/malani/files/otherstuff.zip (ImageTools - also includes an album page)

    Copy & paste the code below to embed this comment.
  2. excellent code and article,

    thank you guys!

    Copy & paste the code below to embed this comment.
  3. Does not work in Safari. I didn’t test it with any other browsers.

    Spits out:

    GIF89ad

    Copy & paste the code below to embed this comment.
  4. Along with “GIF89ad” it also spits out a bunch of unlegible characters.

    Apparently the forum doesn’t allow such characters…

    Copy & paste the code below to embed this comment.
  5. Nice and clean.
    Will be featured at www.phnk.com in a few days. Credits go to author on index page, for sure.

    Copy & paste the code below to embed this comment.
  6. Firebird doesn’t like it either. Looks like an IE-only script. Shame - I can’t use PHP for professional projects and I can’t pull this kind of thing off in ASP myself… Still, a good little article. I already use Dan’s code on my personal site to display random CSS background images. Works beautifully.

    Copy & paste the code below to embed this comment.
  7. Just thought I’d better explain how you can use Dan’s script for CSS background-images.

    In your CSS file, simply put the location of the script in the url() value of the background-image property:

    div#rotateImage {
    background-image : url(/scripts/rotate.php);
    }

    and you’re laughing!

    Copy & paste the code below to embed this comment.
  8. ^^^ Apologies.

    Apparently it doesn’t work as the link I gave is for the actual script itself. The script works well otherwise.

    http://www.duelcom.com/malani/db/img/imgrotate.asp

    This is an HTML page with the image script linked.

    tested in IE/Moz/FB/NN.

    Copy & paste the code below to embed this comment.
  9. Possibly even easier, this script you don’t have to actually edit.  Simply drop this script into the same directory as the images are that you want to change between.

    Example:
    http://www.devnetwork.net/forums/images/faces/randimages.php

    Code:
    http://www.devnetwork.net/forums/images/faces/randimages.phps

    Copy & paste the code below to embed this comment.
  10. This may be beyond the scope of the article, but it would be very cool to have a rotation script that could handle dimensions (for faster layout) and captions/alt text/longdesc (for accessibility) as well.
    There are certainly (nonsemantic) images for which the proper alt text is empty—and for that matter sets of images for which the alt text is always the same, but both additional features would have important benefits for certain groups (of images, and of visitors). I can think of a few ways to handle this—from<ul><li>putting the images, dimensions, alt text, longdesc, and caption info in a database,</li><li>to using a more heterogenous folder with images, text files, and so on, and a common naming scheme (image-j.png, caption-j.txt, longdesc-j.txt, dimensions-j.txt…)</li><li>to embedding the alt, caption, and longdesc info in the IPTC headers and then using one of the open source IPTC parsers to extract them</li></ul>All of those have potential downsides in terms of workflow, but they would also have significant potential benefits as well.
    ...Can you tell that I’m working on these issues for another project right now?

    Copy & paste the code below to embed this comment.
  11. For that matter, can you tell that I didn’t notice the “HTML displays as Source; it does not render.” message?

    Either that, or I just assumed that everyone hear is a native speaker of HTML. Yeah, that’s it…

    Copy & paste the code below to embed this comment.
  12. You just made my life so much easier!!!

    Thanks

    Copy & paste the code below to embed this comment.
  13. We’ve been running a CGI script to do the same thing, inserted as an include into the webpage - drop us a line for more :)

    Copy & paste the code below to embed this comment.
  14. I also wrote a php script like this (don’t have the sourcecode near me athm though) but instead of giving the contents of the image, it redirects the browser to the url of the image using the Header(“Location: “) command.

    This way you can save bandwith since the image can be cached instead of being downloaded over and over again.
    Just my $0.02 :)

    Copy & paste the code below to embed this comment.
  15. There are a couple bugs in this script that together make for a huge security issue. 

    I’ve emailed the author with details.

    Please don’t use this script until the author can post the updated version.  It is a simple fix, so I’m hoping we’ll see the update soon.

    Copy & paste the code below to embed this comment.
  16. One problem with the script is the way in which the list of files is generated.  You can have some problems with operating systems which generate preview icons for the files.  For example on OS X you get hidden files that contain the preview which are very similar in name to the actual image.  The important point is that they also have the same extention.  The filenames start as with a ‘.’ and so do not show up in the Finder but are included in the list of images to circle through.  If the script decides to use one of these images then you will get no content displayed.  The only way to solve this problem (in OS X) is to use the Terminal to delete the icon previews and then not to open the pictures in an application that will generate them again.

    Or you can modify the regular expressions used in the scripts to exclude files that start with a ‘.’.

    Copy & paste the code below to embed this comment.
  17. A small modification—fill an array, then randomly sort—allows multiple images to be selected without danger of showing the same image in two spots at once: see http://www.terriertribe.com/ for an example.

    Copy & paste the code below to embed this comment.
  18. The script works exactly as promised and is useful, but I don’t like that the height, width, and alt attributes are ignored. This causes problems both for accessibility and for validation. Obviously you could stick an alt=”” to help validate, but that defeats the alt purpose.

    Also without dimensions, you can’t reliably float the image.

    Since the server is running PHP you could, in theory, use <% include “rotate.php?alt=alt_text”; %> where rotate.php would generate the entire <img> tag, including height, width and alt.

    Copy & paste the code below to embed this comment.
  19. There are a number of different ways of doing this via ASP…

    Basically it involves consitantly naming your images, ie; image1.jpg, image2.jpg, etc…

    then randomize a number and pass it to your image tag…

    image<%=i%>.jpg

    (obviously width, height, alt should be included)...

    But it’s as simple as that.

    I’ve modified it to drop a cookie on the client for the time their browser’s open, so if they return to the site during the same session, it’ll draw the same image…if the bowser’s closed…then the cookie deletes and they get a new image next time they visit…

    Obviously there’s probably a few other ways of doing this but this one works…

    works for me…

    Copy & paste the code below to embed this comment.
  20. I’ll be interested to see the debugged version of this. I’ve been using a javascript include to do this for several years. It’s fairly simple and when I add new images, I just name them accordingly and edit the maxnumber to equal the highest image number. Seems to work fairly well.

    [removed]
    <!—

    var maxnumber=122;
    var randomnumber=Math.floor(Math.random()*maxnumber)+1;
    [removed] (”/art/logos/”)

    //—>
    [removed]

    Copy & paste the code below to embed this comment.
  21. Always admired Hivelogic’s image rotation, but mainly for the fabulous retro pics. ;^)

    Great article and loving the new ALA look.

    Copy & paste the code below to embed this comment.
  22. ‘scuse me while i’m being a newbie, but i’d also like a “text rotator”, to display random silly proverbs and phrases… and, er… does this sort of things exist yet?
    (i’m sure it does… no?)

    Copy & paste the code below to embed this comment.
  23. … and if the randomly displayed text could use styles, it would be heaven…

    Copy & paste the code below to embed this comment.
  24. I’m using a PHP script to change the background image for our new site that is in development. I’m looking at changing the image for national/state holidays, the seasons, school events, etc.

    Copy & paste the code below to embed this comment.
  25. that was SO easy. luck was on my side today, because i had planned to write a randomizer script after i had read my daily links, but when i saw this article, i didn’t have to write my own.

    thanks dan, you’re brilliant.

    Copy & paste the code below to embed this comment.
  26. Someone earlier mentioned using 302 temporary redirects to rotate the image. When Dan first released this method I wrote something that did this, available here:

    http://photomatt.net/scripts/randomimage

    This has given me some good ideas I’ll incorporate into that script. The header method has another advantage that no file that couldn’t already be accessed through your document_root is available, so you can readfile(’/etc/passwd’) or something similarly nasty like that.

    Copy & paste the code below to embed this comment.
  27. The debugged script is online in the same location as the previous script, namely:

    http://www.alistapart.com/d/randomizer/rotate.txt

     

    Copy & paste the code below to embed this comment.
  28. It’s been fixed and the new version is in place.  If you’ve already installed a copy on your server, consider grabbing the new file.

    Thanks to Justin Greer and Milo Vermeulen for their suggestions!

    Copy & paste the code below to embed this comment.
  29. The script works great for me in Firebird, Safarai, and all other browsers I have tried. Thanks so much!

    -Patty

    Copy & paste the code below to embed this comment.
  30. Thanks for the great script.  Works well in Firebird 0.6.1, Opera 7.11 and Internet Explorer 6.0.  I even got it to work with Konqueror which surprised me.

    Someone mentioned about accessibility and this script earlier.  I decided to add a longdesc of my rotating images to the script.  That way I could define my title and alt tags as Rotating Images…  I got it to validate XHTML 1.1 with no problem.

    Copy & paste the code below to embed this comment.
  31. is it in any way possible to make this script work where each rotating image is linked to a different page…?

    Copy & paste the code below to embed this comment.
  32. Someone pointed out the issue of bandwidth in a comment in my blog. When people are connected to the internet by a dialup connection, they can no longer rely on caching to speed up their surfing, when they have to download a new image every time they enter a site or a new page within that site.

    The fact of the matter is: Some people are still stuck with modems and having to wait a couple of seconds extra for every page to download might be a couple of seconds to much ...

    Anyway, try not to use huge images for rotating purposes. :)

    Copy & paste the code below to embed this comment.
  33. If as the article suggests you want your logo to be the same for a while, you can use their script and add ?img=URL to the query string in your HTML source.  Since the whole purpose of this was to eliminate source editing of the HTML, here’s another solution:

    http://www.troop326.us/jeff/rotate.txt

    I’ve prominently marked the new sections; I’ve just added a new variable for the name of a default image (defaults to “default”), and when img isn’t specified, it searches the directory for any file with that name and an extension in $extList.  The first file it finds it will use.  Now you can just upload a new file of any defined image type with (name==$defaultName) and the script will use it if no img is specified - no HTML editing if you want a certain image.

    Copy & paste the code below to embed this comment.
  34. I tried using the script to rotate several images side by side but the script uses the same image for each iteration.  How can I adapt the script to randomly select a different image for each iteration in a string of images?

    Thanks for your help!!!!

    -Jeffrey Kerekes

    Copy & paste the code below to embed this comment.
  35. One option just occurred to me.  Create several directories of images with the rotate.php script in each.  For three images, for example, you might do something like this:

    /images/rotate/rotate.php
    /images/rotate2/rotate.php
    /images/rotate3/rotate.php

    create three directories with a series of images in them

    /images/rotate/
    /images/rotate2/
    /images/rotate3/

    Thanks anyway. Any other solutions welcome.

    -Jeffrey Kerekes

    Copy & paste the code below to embed this comment.
  36. be sure to edit your rotate.php folder destination:

    $folder = “/images/rotate/”;

    in the second:

    $folder = “/images/rotate2/”;

    in the third:

    $folder = “/images/rotate3/”;

    I hope this helps.

    -Jeffrey

    Copy & paste the code below to embed this comment.
  37. The reason Abhi Malani’s ASP script doesn’t work ‘raw’ in most browsers is because it’s missing a MIME-Type declaration. The bug can be fixed by adding the following lines:

    if (img.indexOf(”.jpg”) !=-1 || img.indexOf(”.jpeg”) !=-1) {type = "jpeg"};
    if (img.indexOf(”.gif”) !=-1) {type = "gif"};
    if (img.indexOf(”.png”) !=-1) {type = "png"};
    //plus any other types of image you want to use
    Response.ContentType = “image/” + type;

    before the final line.
    There’s probably an easier/more efficent way to to this, but it works.

    Copy & paste the code below to embed this comment.
  38. Right on Joshua :)

    The previous version of this script served the image via a binary stream thus increasing the bandwidth, the ContentType declaration was present then. Then i used Server.Transfer and removed it cuz i thought i didn’t require that. I do. Updated.

    Thanks!

    Copy & paste the code below to embed this comment.
  39. Had written Dan about the problem with the previous version of it. The new one works like a song! Must drop him an email Good work!

    Copy & paste the code below to embed this comment.
  40. Hi guys,

    This is well cool :)

    I wondered if anyone know if it is easy to create a photo gallery with this script?

    Foe instance is it possible to have a 3 column 10 row gallery?

    If anyone can help on this that would be great :)

    Thanks
    Karl

    Copy & paste the code below to embed this comment.
  41. Believe it or not I have a client that is demanding a very large site be fully functional in Net 4…does anyone know if this script works in Net 4, because I can’t seem to get it to work…does anyone have a script like this that actually works in Net 4??

    Thanks,

    Amanda

    Copy & paste the code below to embed this comment.
  42. A snip from terriertribe.com/index.php:
    ...
    chdir( “./pics/200x100/” );
    $pics = array();
    $dir = opendir( “.” );
    while ( $f = readdir($dir) )
    {
    $ext = substr($f,-4);
    if ( $ext == ".jpg"
    || $ext == ".gif"
    || $ext == ".png" )
    $pics[] = "./pics/200x100/" . $f;
    }
    closedir( $dir );
    $p = array_rand( $pics, 3 );

    ?>
    <body>
    <div id=“the3”>
    <h1>Terrier Tribe</h1>
    “<?php print $pics[$p[0]]; ?”
      width=“200” height=“100” alt=”” >
    “<?php print $pics[$p[1]]; ?”
      width=“200” height=“100” alt=”” >
    ...

    Hope that helps

    Copy & paste the code below to embed this comment.
  43. Thanks for the tip Steven Spicer!

    -Jeffrey

    Copy & paste the code below to embed this comment.
  44. Works great!

    Is there a way to get ALT text in any of these images?  How have you been thinking about this in terms of screen readers?

    Copy & paste the code below to embed this comment.
  45. I’m wondering if anyone knows of a way to get multiple images to randomize - but keep them in synch. I’m looking for something that will do it on refresh, not rotation.

    I have two graphics on a homepage that need to match up; the client wants 3 different “random” versions of the homepage, meaning 3 different pairs.

    It seems I should be able to set a random number (1-3) and then use this random number to pick which images get displayed. I just can’t find a script to do this.
    Any ideas?

    Thanks,
    Mindy

    Copy & paste the code below to embed this comment.
  46. Found a solution to my own problem; it may not be elegant, but it works. Here it is, if you’re interested.

    [removed]
    <!—
    // Random numbers are generated using Math.random() JavaScript function
    // Whole numbers between 0 and maxnumber
    var randomnumber=Math.floor(Math.random()*3);


    var ar = new Array(
    “images/image1a.gif”,
    “images/image1b.gif”,
    “images/image1c.gif”
    );


    var ar2 = new Array(
    “images/image2a.gif”,
    “images/image2b.gif”,
    “images/image2c.gif”
    )

    //—>
    [removed]

    image one goes here:

    script language=“Javascript”>
    //write the array image corresponding to the random number selected
    [removed](ar[randomnumber]);
    //—>[removed]

    image two goes here: 

    [removed]
    //write the array image corresponding to the random number selected
    [removed](ar2[randomnumber]);
    //—>[removed]

    ~Mindy

    Copy & paste the code below to embed this comment.
  47. Great script! Just what I was looking for.  However, I was surprised to see that it didn’t work with .swf files.  Anyone know how I can rotate .swf files as well?  I have a folder of .swf and static images, all same dimensions, that I’d love to rotate.

    Thanks,
    Dan

    Copy & paste the code below to embed this comment.
  48. Hi all.  I’ve been playing with the script, and the one by Matt, (http://photomatt.net/scripts/randomimage).

    I couldn’t really consider using the script unless it could cope with alt tags too, ‘cause the kind of sites I do need to be squeeky clean in the accessibility department.  I’ve done the following script, but I’m really new to php.  Please could anyone tell me whether it’s going to be any use - seems almost too simple a solution?

    <?php
    /*
      Image rotater, a little bit by Jake Liddell
      Based almost entirely on Matt Mullenweg’s script > http://photomatt.net
      Inspired by Dan Benjamin > http://hiveware.com/imagerotator.php
    */

    // Make this the path containing the text files that you want to include, like “../img/random/”.
    // A blank folder gets substituted to the current directory.

    $folder = ‘./i/r/’;

    // Space seperated list of extensions, you probably won’t have to change this, if your include files are txt.
    $exts = ‘txt’;

    $files = array(); $i = -1; // Initialize some variables
    if (’’ == $folder) $folder = ‘./’;
    $handle = opendir($folder);
    $exts = explode(’ ‘, $exts);
    while (false !== ($file = readdir($handle))) {
    foreach($exts as $ext) { // for each extension check the extension
    if (preg_match('/\.'.$ext.'$/i', $file, $test)) { // faster than ereg, case insensitive
    $files[] = $file; // it's good
    ++$i;
    }
          }
      }

    closedir($handle); // We’re not using it anymore
    mt_srand((double)microtime()*1000000); // seed for PHP < 4.2
    $rand = mt_rand(0, $i); // $i was incremented as we went along

    $res=require(”$folder$files[$rand]”);

    ?>


    To use it, you just have a line like this in your php html file:

    <img >

    and put the script in the same dir.  The script will look for, and include the contents of a random text file.  If you make the contents something like:

    src=“path/img.jpg” height=“175” width=“150” alt=“test alt text”

    your image is loaded, along with all the attributes you want.

    Haven’t tested on anything apart from IE6 yet, but I thought I’d see what you all thought - as I say, I’m really new to php so I don’t have experience of security flaws, etc.  If it does work, though, you could use it for any random blocks of html, not just images.  Just put the html in the text files, and you’re away.

    Cheers,
    Jake.

    Copy & paste the code below to embed this comment.
  49. I wrote random_gallery, which can be found at http://rossbeyer.net/software/random_gallery, that does this kind of thing. It is a Perl program that can be included via server side includes, therefore there isn’t any client dependence. It actually returns a little snippet of HTML, rather than just a location for the src attribute (maybe I should modify it to do that, too).  This allows you to ask for the image, and/or a caption, etc.  The returned HTML is in the XHTML 1.0 standard and has some options for added class names, etc.

    It isn’t as simple as just dropping the script into a directory of images, however, there is a simple .conf file that the names of images need to be added to.

    Copy & paste the code below to embed this comment.
  50. i just got this going and testing in safari and its not working…

    is their a fix for this?

    Copy & paste the code below to embed this comment.
  51. someone asked earlier if this can work with .swf files.  will it?  i imagine all you have to do is add .swf to the $extList
    i haven’t done it yet but hopefully it works.

    Copy & paste the code below to embed this comment.
  52. Ok, I’m trying to view a local file (its not on the server yet, just my comp) and I get nothing, just a red x.  Is there something I’m missing here about php??

    Copy & paste the code below to embed this comment.
  53. Does the page the image link resides in need to have a .php extension, or will just .html do?
    I’ve tried both at
    http://artsaloft.com/rotate.html
    and it doesn’t seem to show up.
    Anyone able to advise?

    Copy & paste the code below to embed this comment.
  54. Hi
    Just wanted to add a big ‘Thanks’
    Installed the script and it worked first time, even mixed in on an asp page.
    Can’t really ask for more than that.
    Keep up the great work, just starting with PHP and it helps a great deal to be able to view these sort of scripts
    Again, thank you .....

    Copy & paste the code below to embed this comment.
  55. All of the rotators I have seen are random. I realize that sequencing might require cookies or some messin’ wit da session, but is it possible (I have no clue) to place all the file names in a text file and have them “walked through” instead of randomized?

    This wouldn’t work for this rotator (I don’t think), but is there another out there that will sequence, maybe even without the cookies, etc.?

    Now that would be cool. Five PAYPAL dollars are yours if you can point me to one that will.

    There, the gauntlet hath been…um, lain.

    Copy & paste the code below to embed this comment.
  56. For some unknown reason, my server won’t process php files unless they have the extension .php4

    *sigh* have to ask tech support about that.
    But the script does work, just fine!

    Copy & paste the code below to embed this comment.
  57. can you make each image link to a differetn site? <a

    Copy & paste the code below to embed this comment.
  58. I cant get any of the scripts to work? I’ve made folders…put them in with the images…made a page with an image…linked the php script?  all i get is a red x…

    Copy & paste the code below to embed this comment.
  59. Sorry, commenting is closed on this article.