19.8. 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.[9]

[9] As we will note later on, this application might also be called a webchat program.

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 it all 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 with wide-open permissions. If you're on a UNIX system, then you can do this (from your shell) to initialize a file for the guestbook program to use:

touch /usr/tmp/chatfile
chmod 0666 /usr/tmp/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:

use Fcntl qw(:flock); # imports LOCK_EX, LOCK_SH, LOCK_NB .... ...

Get Learning Perl, Second Edition 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.