#!/usr/bin/perl -w ###################################### # # guestbook1.cgi # Roll-your-own everything : headers, html, parameter parsing, file i/o . # Note that this one relies on no outside modules or code. # - Jim Mahoney, Jan 2002 ####################################### # Print out a minimal httpd header. # Doing this first ensures that errors will be printed out to the screen. print "Content-type: text/html\n\n"; # Parse any input form parameters. # Note that the method POST sends parameters in through STDIN.) # They arrive as a single key1=value1&key2=value2 string, with a special encoding. chomp(my $params = ); my %paramhash = split /=|&/, $params; my $name = $paramhash{name}; # These two keys must match my $message = $paramhash{message}; # the fields. foreach ($message, $name) { next unless $_; tr/+/ /; # Decode URL-encoding s/%([a-f0-9][a-f0-9])/chr(hex($1))/egi; # See pg 21 in "CGI Prog. with Perl" } # Append the date and message to our guestbookfile. # This file must be writable by the httpd deamon; which on akbar means # user/group = httpd/www. # Here I just made that file world writable, "chmod go+rw" # Also, the file is a shared resource - we don't want two folks modifying # it at once. Here I'm using the perl flock() calls to manage that; # see the "locking files" recipe in the Cookbook, pg 245 my $guestbookfile = 'guestbook1.txt'; my ($WRITELOCK, $READLOCK) = (2, 1); # See the Cookbook recipe. if ($message and $name) { my $date = scalar localtime(); my $text = " Posted by '$name' on $date :

$message

\n\n"; open(GUESTFILE, ">> $guestbookfile") or die "could not open-write guestbook; $!"; flock(GUESTFILE, $WRITELOCK); # Wait for an exclusive write lock. print GUESTFILE $text; close(GUESTFILE); # This also releases the lock. } # Read the guestbookfile. # Ask for a read lock first. # (If we're using locking anywhere, must use everywhere.) open(GUESTFILE, "< $guestbookfile") or die "could not open-read guestbook; $1"; flock(GUESTFILE, $READLOCK); # If some has a write lock, this waits. my @guestlines = ; close(GUESTFILE); # Also releases the lock. my $gueststring = join( "\n", @guestlines) || "No messages\n"; # Print out the web page, including the form to submit more stuff # and the things from the file. print <<"EOF"; Guest Book 1 - roll your own

Guest Book 1

So. Ya wanna sign the guest book?
Your Name:
Message:
 

$gueststring
EOF exit;