Random Image Rotation

One of the challenges facing the modern web designer is to create
sites that appear fresh and new every time a visitor shows up.

Article Continues Below

It’s one thing if the site you’re designing is a news site, for
example, where stories or headlines will be updated on a regular
basis, providing fresh content on the hour — or even more
frequently.  But what about those of us designing sites for clients
with relatively static pages whose content changes infrequently?  How
can we provide fresh, changed content for our visitors on
each subsequent visit, without relying on someone to generate this
content on a daily or even hourly basis?

Changing the page only slightly and in subtle ways can work miracles
for an otherwise ‘static’ website.  For example, imagine a
masthead-graphic that’s different each time someone reloads the page.
How about a product image-link that seems to magically change with
every pageview?

Many sites use this technique to randomize the images they display, including:

Work Smarter#section2

There are a handful of scripts out there that rotate images.  Many of
them are written in JavaScript, but suffer from an important
limitation: in order to add or remove items from the pool of images
to pick from, you need to get in there and edit the code yourself.
Every time you want to make a change. In every page that rotates
images.  But you’re not a programmer, you’re a web developer.  And
adding or removing images from the rotation pool should be an easy
thing.  As easy as, well, adding or removing images from a folder on
the webserver.

Right?

Sure thing! With a little bit of PHP magic, adding this feature to
sites you develop is possible — easy, in fact.  Don’t know how
to code PHP?  Keep reading.  All of the code is already written for
you, and it’s not necessary for you to grasp all of it (or any of it,
really) in order to make this work.

I’ve even written this script so that if it encounters an error, no
images in the image folder specified for example, it will generate an
“error image” on the fly and display that, rather than sending an
invalid image to your browser which will, in turn, display the broken
image icon, which is ugly.

The Requirements#section3

Of course, to make any of this work, you’ll need to be hosting your
site on a webhost that supports PHP (ideally PHP version 4.2 or
newer, but that’s not as important).  Most webhosts these days
support PHP — even those sites running on Windows.  This is
because PHP is not only a powerful web-programming language, but it’s
also Open Source.  It’s been ported to just about every web-hosting
platform in existence, so chances are, your webhost already supports
it.

Are We Done Yet?#section4

Chances are, you won’t need to modify the script at all in order to
make it work on the website you’re designing.  Create a folder on
your webserver, upload the images you’d like to rotate into it.
Then, just upload the script — unedited — into the same
folder. You can then see your rotating images in-action by defining
the script as the source of your image, like this:

<img src="/path/to/images/rotate.php" />

That’s all there is to it. Just sit back and enjoy your randomly
rotating images.

Forcing It#section5

An added feature of this image rotation script is the ability to
specify a specific image.  This might be useful when, for example,
you might like to draw attention to a certain product image on your
site when it’s new, or to “freeze” the rotation for a while.  To do
enable this feature, you just need to specify an “img” value when
calling the script, like this:

<img src="/path/to/images/
rotate.php?img=my_static_image.jpg" />

This will force the script to load an image file named
“my_static_image.jpg” located in the rotation-pool folder.

Customization#section6

You might want to modify the script a bit if, for example, you’d
prefer not to upload the PHP script into your images folder, or to
support additional image filetypes.

The first thing we need to do is identify the folder where we’ll
place the images that will be randomly displayed. We do this with a
simple variable assignment:

$folder = '.';

The easiest way to make this work is to place the PHP script into
the same folder as the images themselves.  Because this is
the preferred method, we’ll set the default value for this folder to
be “.” which is PHP-speak for “the same folder I’m in.”  More
advanced users can to change this to point to a folder by replacing
the “.” with a path to their files, like this:

$folder = '/www/example.com/images/rotate_me/';

Now we need to decide which types of images we’d like to support for
our rotation pool.  At the time of this writing, GIF’s, JPEG’s, and
PNG’s are the most common formats for images on the web.  For this
reason, we’ll start-out with those as our default set of images,
assigned to an extension-list array:

$extList['gif'] = 'image/gif';
$extList['jpg'] = 'image/jpeg';
$extList['jpeg'] = 'image/jpeg';
$extList['png'] = 'image/png';

If you need to add a new file-type at some point in the future, just
copy one of the lines above and customize it by adding your own
extension.

That’s it!  You’re done editing the script.  Just upload it to the
images folder you’ve created, and link as explained above.

Where Are The Goods, Already?#section7

You can download the PHP source right here (4k text file – after downloading or copying and pasting, save as rotate.php).

Have fun!

58 Reader Comments

  1. 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.

  2. 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!

  3. 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

    • putting the images, dimensions, alt text, longdesc, and caption info in a database,
    • 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…)
    • 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

    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?

  4. 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…

  5. 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 🙂

  6. 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.

  7. 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 ‘.’.

  8. 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 tag, including height, width and alt.

  9. 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…

    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.

  10. ‘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?)

  11. 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.

  12. 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.

  13. 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.

  14. 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!

  15. The script works great for me in Firebird, Safarai, and all other browsers I have tried. Thanks so much!

    -Patty

  16. 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.

  17. is it in any way possible to make this script work where each rotating image is linked to a different page…?

  18. 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. 🙂

  19. 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.

  20. 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

  21. 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:



    create three directories with a series of images in them

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

    Thanks anyway. Any other solutions welcome.

    -Jeffrey Kerekes

  22. 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

  23. 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.

  24. 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!

  25. 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!

  26. 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

  27. 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

  28. A snip from terriertribe.com/index.php:

    chdir( “./pics/200×100/” );
    $pics = array();
    $dir = opendir( “.” );
    while ( $f = readdir($dir) )
    {
    $ext = substr($f,-4);
    if ( $ext == “.jpg”
    || $ext == “.gif”
    || $ext == “.png” )
    $pics[] = “./pics/200×100/” . $f;
    }
    closedir( $dir );
    $p = array_rand( $pics, 3 );

    ?>

    Terrier Tribe


    width=”200″ height=”100″ alt=”” />

    Hope that helps

  29. 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?

  30. 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

  31. Found a solution to my own problem; it may not be elegant, but it works. Here it is, if you’re interested.

    image one goes here:

    script language=”Javascript”>
    //write the array image corresponding to the random number selected
    document.write(ar[randomnumber]);
    // –>

    image two goes here:

    ~Mindy

  32. 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

  33. 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:

    >

    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.

  34. 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.

  35. 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.

  36. 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??

  37. 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 …..

  38. 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.

Got something to say?

We have turned off comments, but you can see what folks had to say before we did so.

More from ALA