A Better Image Rotator

About a year ago, I wrote an article, introducing a method for displaying a random image every time someone visits a web page.  Administration was simple: just add or remove images from a folder on the server, and they would appear (or disappear, respectively) from the pool of random images being displayed on that page.

Article Continues Below

There are many benefits to randomizing an image on a web page, one of the most significant being the feeling of freshness it can add to an otherwise static site.  Visitors returning to the page feel that, although the content might not have been updated, something has changed, and the site might be worth revisiting again in the future.

The Downside#section2

Although the implementation was easy, the previous technique could only output the image — there wasn’t a way to link each image to its own specific URL, nor was there a way to have a different alt attribute for each image.  The image would rotate with each page load, but that was it.  Worse, because the IMG tag was static, the images all had to be the same size. So you had random images, but very little flexibility.

The new Rotator changes all that.  The technique described below still picks a random image from a pool of images, but now you can link each image to its own specific URL.  You can also provide custom alt and title attributes for every image.  Now, rather than pushing the image content directly to the browser, the new script simply generates the a href and img tags on the fly, customizing their content based on the random image it selects.

The Trade-Off#section3

Of course there’s always a catch. While the old technique was very easy to manage (just upload or delete a file from the image folder on the server, and you’d change the line-up), the new technique requires a configuration file.  Fortunately, thanks to some PHP goodness, the configuration file is quite simple and easily updated, making the addition or removal of images almost as easy as a simple upload or delete.

Work It#section4

You can see an example of the new technique in action right here. Reload a number of times and watch the images change.  Mouseover each image and watch the URLs change.  View the source and you’ll see the alt and title attributes changing as well.


You’ll need to be hosting your site on a web host that supports PHP (ideally PHP version 4.2 or newer, but this technique should work with older versions as well).  Most web hosts these days support PHP — even those running on Windows platforms.  If you’re in doubt, ask your web host what version of PHP they’re running.

Also, unlike the older version of the random image rotator which could be called by static HTML pages as well as PHP pages, the new version must be called from a PHP file.  This means that the page displaying the image needs to have the .php  file extension (rather than .html).

The Configuration File#section6

I promised that the configuration file would be easy to manage, and, thanks to PHP’s ability to load and understand old-school ini files, it’s a cinch to deal with.  People familiar with older versions of Microsoft Windows will recognize this file format — it’s the same style as the win.ini and system.ini files of yore.

A configuration file providing two images to the rotator might look like this:

  src   = img/ala.jpg
  alt   = ALA Logo
  url   = http://alistapart.com/
  title = A List Apart  [Scientist]
  src   = img/scientist.png
  alt   = Pic of a scientist
  url   = http://hivelogic.com/
  title = Hivelogic

This simple format makes use of blocks to identify the image name, followed by a few rows of keys and their values.  For example, I can create an image entry for a picture of a scientist with the [Scientist] line.  This starts the image entry.  The following lines list the image’s src, alt, url, and title attributes.  The src entry should point to the image on your server just as you’d link to it in a normal HTML document (using a relative or absolute path).  These values are then put together by the PHP script to create a custom-generated, validating a href and img tags. 

But what about the image tag’s height and width elements, you might be asking?  Fortunately, you won’t have to determine and enter these yourself.  The script is smart enough to figure these out for you, on the fly, once it’s randomly selected the image.

So, if the script had selected the Scientist image, it would create the following img tag from the information in the configuration file:

  Pic of a scientist

The link above has been split into several lines for legibility here. In the real-world, the link would appear on one line.


You can view the rotator.php script and a sample configuration file, or you can download them together as a zip archive.  The zip file also contains a sample index.php file demonstrating the PHP code below.

Once you’ve created (or modified) the configuration file, save it as images.ini and upload it to your web server.  You should place the file in the same folder as the pages that will be displaying the images (rather than in the same folder as the images themselves). In other words, this file should be right next to your index.php file, not in a folder beneath it.

While you shouldn’t have to change the location or name of the configuration file, it is possible to do so it if you’d like.  But remember, if you do, you’ll need to modify the random image script as well so it knows where to look for your file.

Next, upload the image rotator script itself.  This PHP script, named rotator.php, should also be uploaded to the same place your main pages live, again, right next to your index.php file.

Then you’ll insert a bit of code into your existing page (which ends in .php, right?) to include the image rotator script; this will prime it for displaying random images anywhere on your page. Including the file with PHP is easy.  Just insert the following line at the top of your PHP page:

  <?php include('rotator.php'); ?>

Now we’re finally ready to make the random image display.  To do this, place a line of PHP code exactly where you’d normally place the img tag.  So, if your existing page looks like this:


Here is a picture of a scientist:


alt="Pic of a scientist"

You would change it to look like this:


Here is a picture of a scientist:

<?php showImage(); ?>

If you’d like, you can duplicate that line on your page anywhere you might want a random image to show up. The images that appear should be different from each other — so if you have enough pictures in your pool, you shouldn’t see the same random image appear twice on the same page at the same time.

What If I Want to Use Different Config Files for Different Pages?#section8

Oh, right. No problem.  Just specify the name of the alternate config file when calling the showImage function.  So, instead of using the line above, your code would look like this:


Here is a picture of a scientist:

<?php showImage('myprecious.ini'); ?>

Where myprecious.ini would be your alternate configuration file, listing an entirely different set of images.  You can do this as many times as you’d like, on any page you’d like, or even multiple times within the same page.

What If I Don’t Want Links?#section9

You might just want to display images without displaying links at all. To make this work, just leave the url value of the image entry in the config file blank, or omit it entirely.  The rotator is smart enough to check for this.  If it doesn’t find a URL, it will simply output the img tag without the surrounding a href tags.

What If I Want a Custom ID or CLASS Elements in the Image Tag?#section10

Yeah, I figured you might.  If you do, just add one or both id and class tags to the configuration file, like so:

  id    = specialImageID
  class = specialImageClass

If the rotator finds them, it will add them to the img tag. They’re totally optional.

You’re Done#section11

Once you’ve included the code in your own PHP pages, just visit them in any web browser and reload a few times to see the effect.  That’s it, you’re done!  Depending on your browser’s cache settings and behavior, you may have to wait a moment after the image has loaded before hitting Reload in order to see the image change. Have fun!

151 Reader Comments

  1. great explanation! I really like this, but I’ve got a question.

    I’d like it to rotate & display more than one image – how would I do that?
    basically, if I’ve got 3 images listed in the .ini file, I’d like each one listed in some random order.
    is that possible with some minimal tweaks?


  2. Nick: If I understand what you’re asking – the order the images are listed in the INI file doesn’t matter, the image being displayed is always selected from the list at random.

  3. Pointman:

    What is your point…man?

    Use XML for what? Are you suggesting he use xml for the config file? How would that be easier? The *.ini file seems nicely formatted to me and easy to use.

  4. As with the other interesting and handy articles published here, I’d like to see a version of this for ASP.NET. I see an XML file, dynamic XML and an XSLT. The demand for ASP.NET equivelents became obvious to me after I created this .NET version of a previous ALA article: http://www.enjoybeingsoftware.com/dev/gen_heading/

    What I don’t see is a great need for random image rotation where the image would be of variable sizing, how could one work that in to a CSS layout without breaking the design?

    Is there a practical example of this technique in usage? The example posted is hardly “real-world”.

  5. You might be right about the fact that XML is ‘the way to go’ but it isn’t an esay thing to pick up…
    INI-files are so much easier and as I remeber ASP.NET can just as easy handle INI files with some built-in functions. (-> justin)

    Anyway, rotators isn’t really a dificult topic anyway, you just make it incomplicated


  6. Here’s a dumb question:

    Did I read the article correctly to understand that all my pages which use this will now be “###.php” and not “###.html”?

    I’m already managing a fairly big site and I don’t want to go back through and change all my links. Is there a way to keep my .html extensions?

  7. There is an AdRotator control that comes with .Net. If you need something special from it just inherit and extend it.

  8. guyPaulo, you might want to look into using the older technique for rotating images, which can be found here: http://www.alistapart.com/articles/randomizer/

    That way your pages can continue being .html or whatever. You could also get even more abstract by using the background-image property of CSS to call the random image generator…



    You can also go into the server configuration settings and map the PHP engine to parse HTML files, but that would add a lot of processing overhead and require administrative access to your server.

    As a side note, you have an entire site that is static? All HTML pages with no backend processing? You must like editing HTML pages and FTPing them a lot! 🙂

  9. guyPaulo: not a dumb question at all. Depending on your web host, there are a couple of ways to handle this. The easiest way would be to tell the server to treat (and parse) *all* html files as if they were PHP files. The performance hit to the server is small, but it’s something to take note of if you have many plain html pages which would be parsed unnecessarily.

    You can place the following code in a .htaccess file at the root of your web folder to enable this:

    AddType application/x-httpd-php .htm .html

    This should handle the switch for you – but again, remember there’s a slight performance hit for html pages that don’t contain PHP as they’ll now be parsed as if they were PHP files.

  10. Narrator:
    what I meant is, if I’ve got 4 images listed in my ini file, I’d like to have all 4 displayed on my page at the same time – but have the script randomize the order each time the page loads.

    does that make more sense?

  11. I agree that changing the .ini file to an xml file would be ideal, especially if it uses some more semantic markup so as not to scare-off anyone who inherits the updating job. Also, a slick programmer could manage the rotation in a database with an added ‘image_group’ field, removing the need for multiple config files and allowing the creating of a front-end application that could manage the files. Altogether I like like the improvements.

  12. Very good article, thank you for sharing. I have an image rotator on my site that uses almost exactly the same idea you have here with just a few differences.

    For one, I don’t use an .ini file. The ini file parser doesn’t like two double-quotation marks in the middle of a value (e.g. James “007” bond) or ampersands (php 4.3.8). This prevents you from linking to CGI generated web pages, for instance.

    Instead I use this for my configuration file:

    $src = array();
    $href = array();
    $alt = array();

    $src[] = ‘/img/image-one’;
    $href[] = ‘url-one’;
    $alt[] = ‘alt-for-image-one’;

    $src[] = ‘/img/image-two’;
    $href[] = ‘url-two?cgi=value&another=cgi-value’;
    $alt[] = ‘alt-for-image-two’;

    Second, I wrap all usage of those values in the script in an htmlentities() call. That escapes characters that might break the anchor or img tags generated by the script.

    Like this:

    echo ‘alt=”‘.htmlentities($alt[$index]).'”‘;

  13. Why only images? Why .ini-files?

    We could as well just include a random (x)html-fragment from a directory (similar to the first roationscript), and with a single script we get image-rotation, or flash-rotation or article-rotation or …..

    The advantage of a configuration file (may it be .ini, xml or database driven) is, that we get some sort of simple documentation in one file for free. But it wouldn’t be complicated to put the html-fragments into one config-file.

  14. I did a little tweak on the php file as well as the include part… I added $_SERVER[“DOCUMENT_ROOT”].”/path/to/rotate.php” same thing with the ini src one the rotate.php itself… but all in all, it really works great and loads fast.

  15. Just an FYI to any of your readers who try this and are having troubles with it: http://bugs.php.net/bug.php?id=28029 is what I learned of when I tried a hack on my blog app that used getimagesize() to (duh) get the image’s size. According to the posts in the blog app’s forum there are different types of buggyness available. I got a long delay before no values were returned, others had a fixed set of values returned, and some had problems with only certain image types or images of rather large byte or pixel sizes.

  16. On the examples in Mozilla and Firefox I see the nasty default border showing in the examples. Did someone just forget or do you not have control over that?

  17. I wonder why you promote this solution with a plain .ini file since PHP ships with a pretty powerful XML toolkit. Why having such a handwritten parser? I support ‘XML is the way to go’.

    Even more I would recommend to implement this script with a database driven system if you want to rotate a larger number of images: As you say most of webhosters support PHP these days they also offer some kind of database like MySQL, PostgreSQL, MSSQL…

  18. I did actually post an update to your original article a year ago, allowing random html rather than random images. This solved the problems of not having alt tags – you could essentially put in any random markup you wanted. I can’t really see why you’d want or need anything more complicated?


  19. True Brant but not only would you have to know about OO but you’d also have to run .NET which would be a shame

  20. It strikes me that with a bit of manipulation of DHTML and PHP the design opportunities for this are endless. There is no reason why XML or MySQL (or any other database for that matter)couldn’t be used as alternatives to the .ini file method. If the site uses a database, use that. The chances are that in a dynamic server side scripted site that uses database connections, these will be open on most if not all pages. If so, the extra load on the server will be negligible when compared to the advantages of building rotator inputs to a content management system so that additional images/content/pullquotes etc, can be added by non-technical users.

    Personally, I will be wrapping up the functionality here in a couple of generic classes that can be added to my PHP development library and called upon when needed. When I have, I’ll drop a post here if Mr Z has no objection.

  21. Hi there,

    In the older version I was ablr to call the script via CSS. Can this be done with this version?


  22. … save bandwidth and user a javascript rotator.

    Attaching images server-side to pages means that the whole document has to be resent when only the slightest bit of html is changed!
    Use embedded javascript instead, where the html doesnt change at all.
    I’d only go for this option on a page that weighs alot, otherwise the php solution is good to go 🙂

  23. I take it this method also allows the client to cache the images?

    I think the previous version returns the file using a Mime type as opposed to passing through an actual URL to the source image. This is in itself a great bonus for us dailup users out there 😉

    Great work though

  24. If you have a large number of images it would be so much easier to store it all in the database together with the rest of the website content.

  25. thanx for the article, it’s good and handy 😉
    i have a problem with the image rotator. It seems to work well, when i open the page where i wanted the image rotator to be, it is there. Though the image itself is not shown only a red cross and the name of the picture. If you click on the cross you activate the link and you get to see the picture.
    What could cauze this problem i am having?

  26. Chris (above) wrote:
    Attaching images server-side to pages means that the whole document has to be resent when only the slightest bit of html is changed!

    Not so. The code gets changed on the server before the web page is sent to the client (browser). The document is sent only one time. This is how all server-side scripting works.

    No bandwidth is saved by using JavaScript instead. JavaScript code must be sent from the server to the client, and therefore most likely adds bytes that are sent over the wire (increase the file size of the web page).

  27. “Next week: your own guestbook!”

    Come on guys these tutorials are of the “beginner” rating. Any programmer with more than a month of experience can figure out how to produce basic materials such as described in this item.

    Can we please get back to the interesting articles about fancy solutions to daily problems?

  28. Larry,

    So you’re saying that even when the html is changed, the page is not sent again?

    You’ll notice a delay in the page rendering if you opt for this method.

  29. Cool.
    To make this a total geeky thing, you could probably write a config panel (as easy as the config file was).
    But then there goes the simplity 🙂
    Very cool script.

  30. I’ll just point that if you have a good cruft-free content manager — Movabletype, for instance — you can have it spurt out the .ini file with either custom fields or just set-up another blog. This would be helpful only if you need to manage a whole lot of random images (rotating nameplates for instance, ala’ typographi.com)

  31. first off, i love all of you. in each of your lives – keep up the amazing work.


    trying a lot of things.
    but im only getting the second image in the ini to load.
    even when switching up the order in the list.
    its always number two that wins.
    all images will load, if i put them second in the ini.

    *beats dead horse*

    im starting to think that no.2 = kaka


  32. The major advantage to using XML over an .ini file is XML allows you to have multiple elements with the same name. And now that PHP supports SimpleXML its easier than ever.

    I’ve written an article on my blog discussing how to do just that. Mind you it is specialized to my needs and it is my first attempt at writing such an article, so go easy on me.


    Sorry about the plug, delete if desired. Although I think the bandwidth hit I’ll get will be punishment in itself.

  33. I think this is a pretty nifty tool. The requirment that all of your pages that use the tool must end in php can be a bit annoying, but I imagine you would be mostly using this tool in a dymanic site where you are already using a fair bit of php code. Besides, it seems like it is pretty easy to fix anyway.

    As for the configuration file, while XML might be pretty and new, I like the ini method which is easy to understand and add to. This technique is about making an interesting design method useful and powerful, not code zealotry.

  34. the script seems to be having problems being random, it calls the second image every time.

    This seems to be the same problem as efa was having.

    Any suggestions?

  35. Has anyone ever experienced a delay with this rotator method? The old version in particular, I would see the entire page download, then the image finally come in. I was using it to write a background image. Would that be related to the size of the image, where it was in the CSS file, how I included the CSS file (@import vs. link)?

    Just wondering.

  36. “Come on guys these tutorials are of the “beginner” rating”

    Yes granted, but not all ALA readers are advanced coders.

    There is more than enough space on ALA to suit everybody’s tastes. I do get tired of readers knocking the articles just because they didn’t find it useful or it was “obvious” to them.

    This is not YOUR webzine. If you don’t like an article then don’t read it, or at the very least keep such comments to yourself.

  37. Thanks so much for this great and easy to use script! While I made something like this in JavaScript the other day, your solution is much more elegant! 🙂

  38. Liked the rotator, downloaded and trialled it locally on my machine, worked fine, uploaded files onto webserver, with structure intact and keep getting the following error message.

    Fatal error: Call to undefined function: showimage() in /home/ridiikn/public_html/index.php on line 18

  39. Yeah, something was funky on my ISP’s server. The script worked fine on my local dev server as is…but once I uploaded to their environment – random was not random.

    Manually seeding before the array call seems to work:

    # pick a random image from the parsed config file
    $img = array_rand($images);

  40. Looks great, seems perfect–but won’t work for me! all broken images like the other poster.

    I e-mailed my host–I bet it’s on their side, as this works so beautifully on so many other sites.

    Thanks a lot.


  41. Using a simple text .ini cought my eye because it was easy for me to implement.

    I too would like an example of adding a caption line. That way I could write something simple in the .ini file and the variable would display my caption. I am all alone and have to teach myself, so any example is like gold.

    I didn’t get much help from all the comments about how XML would be better or how it would be easier to use MySQL. I would love to study an example of that code.

  42. Yes, those comments didn’t help me either 🙂

    If you have a “better way” you really probably should just write your own article, or privately e-mail the authour.

    Richard, as an up and coming PHP student, what did you think about my problem?

    If anyone wants to see it in person:


    Make sure you use that FULL ADDRESS, as I have another “index.html” there. I did try this without that–and got the same errors.

    If I make the php file point to /images.ini, it tells me it “can’t read the ini file”. If I tell it to go to “images.ini”, then it displays the broken image link.

    Either of those two links, however, should work–which is what has me baffled!

  43. Hello,

    Thanks for the great script. I got it to work, but one question remains: how do I get rid of the border? Normally I use “Border=0” in an img tag, how do I get the same result using this script?

    Thanks in advance.

  44. Everytime I reload the page I get one of the first three images in the .ini file. I have five total, and if I move the two ones that never load to the top, they load but the last two don’t.

    I have a random text script also, but it is actually random, so it might not be a server problem.

  45. There was something that you never answer in the other image rotator that I wanted to address to you. You said you can link to the img via Zudomon77@no-spam-yahoo.com

  46. Why php, .net or xml when you can achieve the same result in javascript using less amount of code..? Just create an array containing the desired info and randomly display it through a javascriptfile that you call from the html-page..

  47. Mike, I’d bet because Javascript is client side, and PHP isn’t…

    I’d personally rather stay AWAY from javascript when possible.

    As for the “no borders” questions–

    remember guys, this is CSS!!!! How do you get rid of borders?

    In your css file, you have a line like this:

    “a img {
    border: none;
    }” (minus the “)

  48. This image rotator is great!

    Is it possible to have a group of pictures shown in sequential order for a particular computer? Maybe with a cookie and some javascript?

    Brian Smith
    Albany, NY

  49. Even though I had a capable GD configuration this wasn’t working for me, but I found the problem was using an absolute path like in the ini file like “/images/myimage.jpg” but if I used a relative path “../images/myimage.jpg” all was well in the world.

    Maybe this will help other newbies like me who this script suits just jim-dandy.

  50. I had a similiar problem with the last images not showing up, and also parts of URL’s being cut off (those with query strings). The problem was having a character that parse_ini_file couldn’t deal with like an “=” in the url or a “!” in the alt line.

    The fix is to enclose it in double-quotes like this:

    alt = “XML! Why would I want to parse XML for 3 images?”
    url = “path/to/file?with=querystring”

    Wish that tip would have been in the article, I’m just a newbie and that would have saved me a bunch of time and hair.

  51. Another idea would to make a table in phpMyAdmin with pic- date on- date off- link fields . Have the php script check the server date and show the image (with appropriate link) on the page .A form could then be used to enter the information so the webmaster would have only to set up the images(maybe with the images showing and radio buttons to choosethe image) and someone administering the website could make the changes.

  52. Ok this works for small images, but, what if the images i want to display need to be broken into four sections can the code be modified or is there a better solution?

  53. I used the basic rotator without the *ini file. I called the image from using the but my page would not validate. I did not realise you could call .php from in a css background selector. Awesome work. Thanks a lot dude.

  54. Having a bit of trouble getting it to work. It looks way simplier than the ‘javascript’ rotator I have been using. The code to placed at the top , is that top of the body or in the head or at the top of the file?

  55. Hello,

    due to the lack of dynamic pages (I let Movable Type generate .html files where ever possible) I still use the old image rotator. If you have a look at our website, e.g.


    where the large picture at the top is delivered by the image rotator php script. If you click through the site the picture never changes, though – if you reload a page – the picture changes once but then stays for the rest of the site. Is this a kind of caching isue?

    Yours, Yves

  56. Hello,

    due to the lack of dynamic pages (I let Movable Type generate .html files where ever possible) I still use the old image rotator. If you have a look at our website, e.g.


    where the large picture at the top is delivered by the image rotator php script. If you click through the site the picture never changes, though – if you reload a page – the picture changes once but then stays for the rest of the site. Is this a kind of caching isue?

    Yours, Yves

  57. Thanks for the article.

    I am curious about the question mark at the end of the line in the line:
    $id = $images[$img][‘id’] ?

    Why is it not a semicolon?

    If this is a conditional statment I could not find any PHP documentation.

    I also had to add the line:
    srand ((float) microtime() * 10000000);
    before the rand_array .

  58. I tried to use this easy way of random showing images on a site that uses frames. Using the url to point to other pages is no problem since the referred page can be shown in the same frame, but that is obviously not so with an image that links to another site. So, is it possible to add something like:
    target = blank
    to the ini-file?

  59. Somebody was asking about using this script without having to change all their .html files to .php. Well, if you’re running on Apache then chances are you can use a Server Side Include (SSI) call to insert the script’s output into your HTML. You’ll need to check with your host about support, but if you can do it then something like this should work:

    Just get the script to output the entire IMG tag, and put the above line where the IMG tag would be.


  60. I want to implement rotating .swf files on my site. I tried to just call them up as images in th .ini file, but to no avail.

  61. Great article – Can someone post the code on how they would use the class and id tags, both on the .ini file and the index.php file?

    I am trying to “style” the way the image appears when called up by the rotator script. (I would like to get rid of the standard “a href border” around the image.

    Thanks much – and any help appreciated.

    Rob H

  62. Does ALA not even bother to maintain their forums anymore? Where’s apartness when you need him. Oh yeah…he has a daughter now.

    I tried to port this method to generate not just one image, but five. I cannot get it to work.

  63. Hello,

    Personally I love the Random Image script. I was just wondering if someone could please help me figure out how to add a target to the A HREF tag.

    Many Thanks!

  64. Dan:
    First of all, great script!
    Secondly, it is a common practice for guys like me (certainly no PHP experts) to want to implement scripts without realizing that special characters can cause big time problems. Let me give you an example in your rotator.php script.
    Please TELL everybody that one MAY NOT include ! in the title line of the images.ini file.
    If your configuration page warned about this, I certainly missed it. So:
    title = Donald Trump lives at a casino (works)
    title = Donald Trump lives at a casino!
    (does not work!!!!!!)
    This can cause people like me to go crazy trying to fix a perfect working script!

  65. hi guys,

    great article. Have a question though.. it would be nice to have images with some hotspot-links in them. I mean not the entire image pointing to an url link, but the image would have different parts pointing to different urls ?

    how can this be accomplished ? any ideas..


  66. I have read the above and it did state that the code would correct the sizing automaticly, but in mine it did not i am using the code above and was wanting to know in this code is there a way to addin the width or height. A very specific code that i can copy and paste would help. Or a step by step comfig in english would help.

  67. there’s something about random image rotation that’s fun to think about.

    i built one of these using php/mysql. you can set up fields for width, height, title, photographer_id and whatever information you want to associate with each image. get a random image_id each time by using the mysql funtion rand() to randomly order the returned rows. then just limit or display the first row. an example sql query…

    select image_id, photographer_id, title, image_path from images_random order by rand() limit 0, 1

    you make a database call each time a page loads, but it works as fast as any other random rotator i can recall.

    in the admin area set up a page that lets admins add/delete images from the server while keeping the database updated.

  68. Brad,

    if you want your solution to work with border=0 then you need to qualify that in the code.

    Something like
    $border = $images[$img][‘border’]!=null ? sprintf( ‘ border=”%s” ‘, $images[$img][‘border’] ) : ”;

    If the border element is set to zero then the statement as is written in your code will always return false and a blank.

  69. This is on the face of it an excellent idear to have a php script that can be included in a php file that rotates various images round each time you load up the page….

    However I have tried to get it to work a number of times and failed completely.. the script uses an ini file and sometimes shows a jpg file I have on the server but somtimes fails to load a picture and instead just shows a tiny red cross and no image….

    It is very disappointing that it appears not to work correctly
    I would like to accept e mail about this in an attempt to correct this.. but feel that there must be several things wrong, either with the format of the ini file or the rotator.php script or both………..

  70. it’s extremely slow… been testing the script, watching the ‘activity viewer’ as it downloads the test-page, sometimes it loads fast, but most of the time the download of the page grinds to a halt when it starts downloading the rotator.php file

  71. This script will only use the first image listed in the .ini file. I tried messing around with rotation.php but nothing worked.

    From what I can see, either the ini isnt working correctly, or the rand() command isnt working for some reason.

    Can anyone help me here?

  72. well i know whats breaking it, but not sure how to fix it 😉

    the problem is the .ini files. if you have an url with a querystring appended to it, the array that parses the ini trips over and everything explodes in a big flaming fireball.

    please please mr benjamin can you implement querystring support?

  73. well, i fixed it. if your url has a querystring in it. wang some quotes around the ini entry.


    url = “think.php?id=43&category=life”

    thanks for great little script benjamin.

  74. I can get this to work, but I am having trouble with using it in sub-directories. Ideally, I want to be able to use this with some variables.

    For example, I want to set a variable for the root directory so that the “rotator.php” can be accessed by going to to the root level ($root/rotator.php). However, when I try to do this, I get an error with the showimage() function (Fatal error: Call to undefined function: showimage() in …)

    Any ideas of how to fix this?

  75. Is there a way to rotate images on a certain interval using only PHP? or at least clean JS? I was thinking of implementing a session ID… but that requires session code on each page. Any suggestions?

  76. I found a way to put several links at different places from the loaded image. I used CSS Style sheet.
    For the moment, my new site is visible at :
    As you can see, “image rotator” generates a random image on my first web page. And one can click on various links.
    If you are interesting by this. Contact me.
    Flip flop.

  77. I’m getting the error

    Unable to read ini file.

    Can anyone help? It’s got the correct code inside and is in the correct folder.

  78. Just for saying that the exemple is now visible at :


    As you can see, “image rotator”? generates a random image on my first web page. And one can click on various links. If you are interesting by this. Contact me. Flip flop.

    METTRE PLUSIEURS LIENS SUR L’IMAGE chargée par rotator !!!

    Juste pour dire que le lien qui montre l’exemple a changé. L’exemple est maintenant visible sur la page d’accueil de mon site (une fois sur la page, réactualisez le site et l’image change) :


  79. I did not see a solution to the previous post on this problem, and would like to add that I get the folowing error message:
    Warning: Error parsing images.ini on line 3 in Unknown on line 0

    this displays on the line above the image that displays.

    Any help appreciated.

  80. Your script is good. But when i used it, I ran into 2 problems. It was slow in retrieving each random image. But it also created firewall problems on two different machines. For this reason i had to stop using it. I currently use the solution given at http://www.tutorialized.com/tutorial/Simple-Image-Rotater/790. This is a block of code you insert into your main php file and does not reference an external file. This seems much quicker than the ala solution and also have had no firewall problems. However, I want to thank you sincerely for introducing me to the concept of image rotation.

  81. I can’t seem to get the script to parse more than two sections. Is this a limitation of the php function or am I doing something wrong?

  82. The rotator script works beautifully. However I want to rotate .swf header movies on my home page. I guess I would need to change the $extLit value, but what would that be to display random .swf movies?


  83. I too would be interested in a way to display the title under the image. As it sits now, it’s not useful for my application.


  84. Unfortunately, our servers at work do not support PHP. Can someone post a link to a non-PHP method. Preferabley ColdFusion or Javascript. Thanks!

  85. Microsoft Visual Studio 2005,which has got an component called “AdRotator”.I really like it,it works as well as the author’s work.Thanks to the author, now I know how it works.

  86. i put all the code in a folder called artist, and when i say nothing happens….please help im new to php!!

  87. Yes, adding a caption is possible. First, add a caption variable to the script:

    $caption = $images[$img][‘caption’];

    Next, edit the script to incorporate the caption variable into the HTML ouput. Something like this:

    if ($caption) {


    ‘, $caption);

    Last, add a caption line to each block in the .ini file.

  88. Not sure why, but the first part of that PHP code got a little munged in transit. I’ll take another stab; perhaps the ALA admin would be good enough to help if it comes out wrong again? :).

    #get the caption

    $caption = $images[$img]['caption'];
  89. .

    I am using Gallery 1.X.

    Right now everything is in this path, images, rotator, index, .ini, … Everything. …


    That works.

    But I just cannot get it included in the actual gallery pages. … On this page I have a random image. …


    I would like to replace that Random image with a RandomImagePlusLink, like this BETTER IMAGE ROTATOR tool generates in rotateJax.

    Since Gallery has a bunch of includes, The index is in the gallery folder, where would I place the folder with my images, my ini file, my rotator, and what would my php include say? …

    How do I address paths in PHP?


  90. I can get the gallery front page to work, but when I bounce off the page and navigate to another gallery page with a set of albums, then try to go back to the top page, I get an error. …

    I am not a wood nymph, but I think there is a troll in my machine.

  91. I am hoping that someone can help me figure out how to have the links open in a new browser window. Does anyone know where I need to put the “target=_blank” command in the ini or the configuration file?

  92. I have been using your ROTATOR script for about a year and I really enjoy its performance. I have approximately 200 images on my web site that I rotate. Each image is linked to a synopsis of a book. I was using one images.ini file but found that many of the images repeated before all of the images were displayed. Many of the images are never displayed. I broke the images file into 12 different files and that improved the performance but I still have the problem that images repeat before all are displayed.

    Is there a method that will insure that all images are displayed before any one is repeated?

    I have also tried to implement the CAPTION mod but I could not get it to work. Thanks for any help you can provide.


  93. A friend refered me to your post. I have used a similar block of code for a random image module. //Spit it out
    // $size=getimagesize(“$directory$image[$randNum]”);

    $filename = “$directory$image[$randnum]”; // Slipstream our content into the template
    eval(‘$home[$mods[‘modid’]][‘content’] = “‘ . fetch_template(‘adv_portal_random_video’) . ‘”;’); ?>

    I’d like to know how I can make it call the most recently uploaded image, rather than a random one.

  94. Can anyone tell me what I am doing wrong? I have added the caption mod but it wont work.

    I also added caption to the ini file like this.

    src = /images_used/067188770X_small.jpg
    alt = Betty Crocker’s Vegetarian Cooking
    url = /usedbooks/cookbooks.htm#Betty Crocker’s Vegetarian Cooking
    title = Betty Crocker’s Vegetarian Cooking
    caption = Betty Crocker’s Vegetarian Cooking


    # file containg your image descriptions

    $IMG_CONFIG_FILE = ‘images.ini’;

    # You shouldn’t need to change anything below this point

    function showImage( $ini=null ) {
    global $IMG_CONFIG_FILE;
    # if no custom ini file has been specified, use the default
    $ini_file = $ini ? $ini : $IMG_CONFIG_FILE;
    # read the config file into an array or die trying
    $images = @parse_ini_file($ini_file,true);
    if (! $images) {
    die(‘Unable to read ini file.’);
    # pick a random image from the parsed config file
    $img = array_rand($images);
    # get the selected image’s css id if one exists
    $id = $images[$img][‘id’] ?
    sprintf( ‘ id=”%s” ‘, $images[$img][‘id’] ) :
    # get the selected image’s css class if one exists
    $class = $images[$img][‘class’] ?
    sprintf( ‘ class=”%s” ‘, $images[$img][‘class’] ) :
    # get selected image’s dimensions
    $size = @getimagesize( $images[$img][‘src’] );
    # if an url was specified, output the opening A HREF tag
    if ( $images[$img][‘url’] ) {
    # output the IMG tag
    # if an url was specified, output the closing A HREF tag
    if ( $images[$img][‘url’] ) {

    $caption = $images$img;
      if ($caption)  {


    ', $caption); } } ?>
  95. I have the script running perfectly on my own laptop testing server, but when i uploaded the pages to the web, I get the above error.

    can anyone shed any light on the subject.

    the include statement is in the correct place at the top of the page, and as i said works fine on my laptop.

    thanks for all your help in advance.


  96. I had a reaaly good ranking in Google – until i rolled this out on my entire site. I have consitently held a rank of between number 1 to number 3 of the search results for atleast the last 6 months. If search rankings bother you, consider something else.

    Those having troubles with it finding the INI file… I had to enter my full server path to the ini file. If you dont know this your host will be able to tell you.

  97. I can’t get the captions to work… this is what I put in the .php file:

    # add caption
    $caption = $images[$img];
    if ($caption) {


    ‘, $caption); }

    and added “caption = ” to the .ini file. Can someone help? Thx.

  98. I have your script working on my site and am wondering if there is a way to give each image a click-through address?

    I am asking because the images that I want to add to our site are ads.

    Thanks for the great script! This is my first excursion into PHP and it worked perfectly without any hitches at all.

  99. I liked the simplicity of rotate — except that since it had an image
    path that was fixed, the browser would cache that image. So if I used
    it as part of my sidebar menu system then it would not change the image
    as I moved from page to page, unless I explicitly reloaded the page.

    I like rotator’s actually writing the link in, and the various features for adding information to it.

    In the long run I can see the possiblity of a suite of similar tools.

    With rotator you must hand edit a file for the directory. It would make
    better sense to write a file per image. Give the text file the same name as the image file, but a different extension. In this way, the manipulation
    of the file and the image can be done together, without messy edits.

    This also allows for the non-existence of the extra information.

    I’m brand new to php, but I’ve done some perl before. I’m going to try
    to make a minimalist rotate that writes image links, using bits from
    both programs.

    Thanks for the two progs.


    Much of the time there is no need to specify the size of the image. That can be offloaded to the browser. Use your css to specify how big
    you want the image to be in the containing div.

  100. I’ve found this code quite useful, but I too am trying to figure out where to insert a TARGET=_BLANK so as to open links in a new window.

    also of secondary interest would be to add a Border=0 feature

  101. Does anyone get the error messages on lines 44 & 48 of the rotator.php file saying undefined index. I don’t need the id for styling, but have created the id in the style sheet to see if it goes away and it doesn’t. It doesn’t affect the rotator when uploaded but I hate error messages on my testing server. Any help??

  102. In order to get only unique images add the following to rotator.php script above the ‘get the selected image’s css id if one exists’ statements (note: you only require one ‘pick a random image from the parsed config file’ statement):

    //initialise array if it has not been created
    if ( empty($_SESSION) ) {
    $_SESSION[‘selected_pics_array’] = array(“0”);

    // pick a random image from the parsed config file
    $img = array_rand($images);

    //ensures that the image is unique
    while(in_array($img,$_SESSION[‘selected_pics_array’])) {
    $img = array_rand($images);

    //add the image to the list of displayed images
    array_push($_SESSION[‘selected_pics_array’], $img);

    Also put the following above your tag:

    After adding all of your “” statements add the following:

  103. I am new to PHP but the script is working fine for what I want…only how do I get rid of the border that is automatically being added to my photos? I dont want a border at all…


  104. Going way back to #4’s request. Can this script be adapted to display only text links instead of banners. I haven’t had any success isolating the ‘caption’ part and suppressing the image

  105. I had this same problem when I switched local server. Everything had previously worked fine.

    I found that if you created both an ID & Class in the stylesheet and left the ID blank (but the Class specified) it corrected the error.

  106. Javascript, with a timing loop and a lot of images addressed by their array numbers, is fine for slower rotating where the images will certainly have time to load, or where you’ve done preloading. But experiments have shown me that if you don’t want people waiting for preloads, or if the image size is quite large, or, especially, if the rotation speed is fast (under a half second), there’s a better way. Having tried a rotator doing 600×400 images at 1/3 second, with and without preloads, I found that the browsers went nuts. I use smaller images and 1 second times and standard Javascript image cycling with no problem, but the browsers draw the line at the bigger/faster combo. So guess what works perfect on all browsers? I made an 800K gif with lots of images in it and 1/3 second timing, using ImageForge and MS Gif Animator. I expected browsers to choke on this since no preloading occurred. But they all smiled, winked, and purred! I hope this helps anyone who’s tried to make rotators work with big, fast images and tore his hair out at the results.

  107. If you are trying to get rid of the border it is probably not an image border but a ‘link border’. This worked on my page:-
    A:hover{color: red; text-decoration:none}
    a img {border:0;]
    The first line just sets the hover attributes the second the link border.
    Secondly you can set the script up to reference different ini files on the same page allowing different pools of images on different places on the same page by renaming the function ‘showImage’to showImage1, showImage2,showImage3 etc and saving each changed file as a separate rotator.php file. ie rotator1.php, rotator2.php etc. The image is called by <?php showImage(‘images2.ini’); ?> or
    <?php showImage(‘images3.ini’); ?>
    This might be inelegant but it works . . .

  108. Excellent information here cause in my language, there are not much good source like this. This interesting post made me smile. Maybe if you throw in a couple of pictures it will make the whole thing more interesting.

  109. I just wanted to say thanks! I extended your script to provide a random image for the side and then I grabbed all the images and randomly selected their order to make a group of thumbnails. Perfect for a new webcomic facebook app I made.

    Thanks again!

  110. Thank you for great article and code. Just found this when getting frustrated with trying to use a JS to rotate images. Now my client – my wife! – wants the images to rotate every x seconds as opposed to reload. I know I can do it in JS, but can this be done in php, is there an easy fix/addition to this code to do it? Any suggestions appreciated.

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