Serving Some Files Randomly

Today I noticed that I have a directory filled with a whole bunch of files that I'd like to use, but I can't make up my mind as to which ones are best. Here's a list of files in that directory:

Directory: /home/httpd/html/web

LinusTorvals.jpg
annette.jpg
changls.gif
fruit.jpg
gates.jpg
gates007.jpg
off.jpg
sly.jpg
vase.jpg
water.jpg
windows.jpg
So, I'll write a small CGI script to randomly choose a file in that directory and display it in a web browser. For example, take a look at the following image and the HTML used::

<img src="http://24.0.195.202/cgi-bin/random1.pl">
You can see that your web browser has displayed the image returned by the random1.pl Perl script. I don't know which image you're currently looking at, but if the web server is working, it will be one of those listed above.

Take a look at the source code for random1.pl. You'll see that it is quite simple. It gets a list of files in a directory and then randomly selects one. Finally, it uses the Location: header to redirect the client to the file it has selected.

One annoying problem related to returning a random image is that your web browser (Netscape, MSIE, etc.) will cache the result. In other words, even if you press the Reload button in your browser, the image displayed will remain the same.

The solution to this problem is to use the Expiration HTTP header. This header tells the browser when the content expires. After the expiration date and time, the browser will retrieve the content again. Look at the script random2.pl to see how to set the headers.

The following example shows the differences in action:

Compare Two Randomly Selected Images

The following table shows the differences (marked in red) in the headers from the two scripts.
random1.pl - no expiration random2.pl - with expiration
HTTP/1.1 200 OK
Date: Sun, 15 Mar 1998 23:23:54 GMT
Server: Apache/1.2.4
Last-Modified: Sun, 15 Mar 1998 22:46:21 GMT
ETag: "11e860-362e-350c5a3d"
Content-Length: 13870
Accept-Ranges: bytes
Connection: close
Content-Type: image/jpeg
HTTP/1.1 200 OK
Date: Sun, 15 Mar 1998 23:20:47 GMT
Server: Apache/1.2.4
Expires: Sun, 15 Mar 1998 23:20:47 GMT
Pragma: no-cache
Last-Modified: Sun, 15 Mar 1998 22:46:28 GMT
ETag: "11e85b-2404-350c5a44"
Content-Length: 13870
Accept-Ranges: bytes
Connection: close
Content-Type: image/jpeg

The same script can be applied to send any type of data, including plain text, HTML, java applets, and audio files. Using the Expiration header guarantees that the user will see a fresh file every time that the script is activated.

So, has this article useful to you? Have any questions? Let me know at the address below.

Author: Doug Steinwand
Date: [03/17/98]

More articles about CGI
More articles by Doug Steinwand
Author Biography

/body>