Creating a Guestbook Program

If you have followed the examples above, you can now get some simple CGI programs going. But what about harder ones? A common request is to create a CGI program to manage a guestbook, so that visitors to your web site can record their own messages.[103]

Actually, the form for this kind of thing is quite easy—easier in fact than some of our ice cream forms. Other matters get trickier. But don’t worry, we’ll explain everything as we go.

You probably want guestbook messages to survive a user’s visit to your site, so you need a file to store them in. The CGI program (probably) runs under a different user, not as you; therefore, it won’t normally have permission to update a file of yours. So, first, create a file (make sure it has read-write permissions for whatever user your program runs as). You can either use a text editor to create an empty file, or do something like:

            > echo. > c:\temp\chatfile

Okay, but how will you accommodate several folks using the guestbook program simultaneously? The operating system doesn’t block simultaneous access to files, so if you’re not careful, you could get a jumbled file as everyone writes to it at the same time. To avoid this, we’ll use Perl’s flock function to request exclusive access to the file we’re going to update. It will look something like this:

# Perl 5.004 use Fcntl qw(:flock); # imports LOCK_EX, LOCK_SH, LOCK_NB .... flock(CHANDLE, LOCK_EX) || bail("cannot flock $CHATNAME: $!"); # ActiveState distribution $LOCK_EX ...

Get Learning Perl on Win32 Systems now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.