One of the challenges facing the modern web designer is to create
sites that appear fresh and new every time a visitor shows up.
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:
- Hivelogic (rotating masthead)
- SimpleBits (rotating sidebar photo)
- Cooper (ever-changing top-images and faces)
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!
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)
excellent code and article,
thank you guys!
Does not work in Safari. I didn’t test it with any other browsers.
Spits out:
GIF89ad
Along with “GIF89ad” it also spits out a bunch of unlegible characters.
Apparently the forum doesn’t allow such characters…
Nice and clean.
Will be featured at http://www.phnk.com in a few days. Credits go to author on index page, for sure.
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.
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!
^^^ 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.
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
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
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?
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…
You just made my life so much easier!!!
Thanks
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 🙂
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 🙂
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.
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 ‘.’.
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.
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.
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.
Always admired Hivelogic’s image rotation, but mainly for the fabulous retro pics. ;^)
Great article and loving the new ALA look.
‘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?)
… and if the randomly displayed text could use styles, it would be heaven…
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.
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.
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.
The debugged script is online in the same location as the previous script, namely:
http://www.alistapart.com/d/randomizer/rotate.txt
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!
The script works great for me in Firebird, Safarai, and all other browsers I have tried. Thanks so much!
-Patty
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.
is it in any way possible to make this script work where each rotating image is linked to a different page…?
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. 🙂
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.
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
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
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
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.
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!
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!
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
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
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
Thanks for the tip Steven Spicer!
-Jeffrey
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?
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
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
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
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?
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.
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.
i just got this going and testing in safari and its not working…
is their a fix for this?
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.
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??
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?
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 …..
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.
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!
can you make each image link to a differetn site?
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…
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
Humility: An Essential Value
Personalization Pyramid: A Framework for Designing with User Data
Mobile-First CSS: Is It Time for a Rethink?
Designers, (Re)define Success First
Breaking Out of the Box