<p>
<form method="post" action="http://your.server.com/cgi-bin/book.pl">
Name: <input type=text name="name" size=30><br>
Email: <input type=text name="email" size=30><br>
Homepage name: <input type=text name="www" size=30><br>
Homepage URL: <input type=text name="url" size=30><br>
Comments:<br>
<textarea name="body" rows=3 cols=45 wrap=virtual></textarea><br>
<input type=submit value="sign in">
</form>
<p>
<hr>
<p>
<!--add-->
</body>
</html>
|
 |
This file has a similar form to the ones used in our other examples. Notice that there is an HTML comment, <!--add--> , at the bottom of the page. This is our marker, hidden from users, that we will use to add new entries to the page:
 |
The guest book form is a bit larger than the others, but otherwise quite simple. Here, you see text from previous visitors. |
Now for the book.pl script. We go ahead and set up all of our variables at the top of our script, which makes it easy to add alterations later:
#!/usr/bin/perl
#variables that will be used later.
$guestbookreal = "/real/path/to/guestbook.html";
$return = "http://your.server.com/path/to/guestbook.html";
|
 |
As with our previous examples, we next need to decode the form information and turn it into useful data:
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
@pairs = split(/&/, $buffer);
foreach $pair(@pairs) {
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$value =~ s/<\!\-\-.*\-\->//g; # get rid of SSI
$in{$name} = $value;
} |
 |
Now we open the guest book file and read all of its information into a variable that we can use in our script:
open (FILE,"$guestbookreal");
@LINES=<FILE>;
chop (@LINES);
close(FILE);
$SIZE=@LINES; |
 |
Now that we have the contents of the file, we are ready to add the new input. We open the file again, this time to overwrite it with the new information. Again, we can use the HTML comment as a marker so that we'll know where to insert new entries. We add the visitor's information to the page, as well as a link to their email address and Web page, if available. Then we close the file:
open (GUEST,">$guestbookreal");
for ($i=0;$i<=$SIZE;$i++) {
$_=$LINES[$i];
print GUEST "$_\n";
if (/<!--add-->/) {
if ($in{'email'} ne '') {
print GUEST "<b><a href=\"mailto:$in{'email'}\">";
print GUEST "$in{'name'}</a></b>:<br>\n";
} else {
print GUEST "<b>$in{'name'}</b>:<br>\n";
}
if ($in{'www'} ne '') {
print GUEST "<a href=\"$in{'url'}\">";
print GUEST "$in{'www'}</a><br>\n";
}
print GUEST "$in{'body'}<p>\n";
}
}
close (GUEST); |
 |
Finally, we send a header to the Web server, telling it which page to transmit to the user. In this case, we send the user the guest book, which now includes their entry. It's a good idea to keep a backup of this file and edit it for length and inappropriate text:
print "Location: $return\n\n"; |
 |
See the complete Perl code.
|