The Hiveware Image Rotator, shared by Mr Zeldman, does one thing and does it fairly well: it shows a random image on each reload. However, the approach the script takes is slightly flawed, and could be improved as detailed below.
My first issue with the script is that it is really only set up to handle two types of files, GIF and JPEG, and then only with the file extensions of .gif or .jpg, so something like .jpeg (fairly common) would not be included. Not to mention the noble PNG is left out entirely. Fixing this, however, leads us to a more fundamental problem: the images are served through the script. This means that the script has to handle the
content-type header, something that is messy to do. A better method, I propose, is for the script to merely serve a temporary redirect header, which sends the browser with a minimum of overhead to the actual location of the file, which has a number of tangential benefits including that it allows the image itself to be cached properly, either by a caching server or the browser itself, and it delegates content negotiation and such to the web server, which is most likely infinitely better at it.
So now what we have a script which reads files in a directory, grabs the ones with a user defined set of file extensions, and sends a simple
Location header to whichever file is randomly chosen. The complication now that the location of the image is now important in terms of the web server document root. One bonus of Dan Benjamin’s method is you can use images outside of the web root, though I don’t know why anyone would want to do this. The script could ask for two variables to be defined, the absolute path to the images and the path to the images through the web server, but I would like for this to be as ridiculously easy to setup as possible. Another option would be to subtract the $DOCUMENT_ROOT variable from the absolute path given and use that, but that would require people to know the absolute path of the directory they’re using, and like I said I’d like this to be easy as humanly possible. The best solution is to use a relative path; if the users enters nothing it’s assumed that the images are in the same directory as the script but if they aren’t the path can be entered in a relative manner, like “images/random” or “../rand-img”. Easy peasy.
Finally, instead of the plain
rand() we’ll use
mt_rand, which is about four times faster and slightly more random. What do you get? The Photo Matt Random Image Script. I’ve tested it thoroughly, but if you have any problems don’t hesitate to let me know. It’s just standard HTTP though so I don’t foresee any trouble. Something neat about this is that with the code we just wrote, you can also serve random anything—from zip files to MP3s—just by changing the extension line. Enjoy! Here’s an example of it in action, you should recognize some of the images as the delightful graphics Jeffrey has been putting up, the rest are snips of photographs I haven’t uploaded yet.