JavaScript: Tool of the Devil

An astute reader writes:

I noticed that the <img src> tag for your rotating header points at a PHP script.

I’ve usually seen this done with JavaScript. How (and why) are you doing this with PHP?

First, the last part:

You do this with PHP because you do not like the inconsistent, erratic, and irregular implementation of JavaScript in modern web browsers. In fact, no two browsers, not even different versions of the same browser, support JavaScript the same way. Some don’t support it at all.

The first rule of Hivelogic is: Do not use JavaScript.

The second rule of Hivelogic is: Okay, use it sometimes, but only when you have no other choice and you know your users will be able to support it, and do so in the most cross-browser-compliant way you can, which is almost impossible, so refer to Rule #1.

Lastly, the first part:

How do you use PHP to deliver a random rotating image? It’s quite simple: Toss a bunch of images (either .gif or .jpg for now), all the same height and width (or they’ll be scaled and stretched by the browser, which looks terrible) into a folder somewhere. Feel free to add or remove images from the folder at any time. The script will pick randomly from whatever it finds.

Now you’ll use PHP to get a list of files in the folder you’ve specified, randomly select one of them, and stream it (prefaced by the file’s content-type) to the browser. Just paste this PHP code (or download it) into a file with a .php extension and save it somewhere:


$fileList = array();

$folder = "folder_where_you_put_the_images";

$handle = opendir($folder);

while (

false !== ( $file = readdir($handle) )

) {

if (

substr($file, -4) == ".gif" ||

substr($file, -4) == ".jpg"

) {

$fileList[count($fileList)] = $file;




$randNum = rand( 0, (sizeOf($fileList) -1) );

if (

substr($fileList[$randNum], -4) == ".gif"

) {

header ("Content-type: image/gif");

} elseif (

substr($fileList[$randNum], -4) == ".jpg"

) {

header ("Content-type: image/jpeg");




To keep things simple, you often put the .php file in the same folder as the images, and set $folder = “.” (which means “I’ve got your images right here, buddy”).

More articles in the Archive →