📄 ch20.htm
字号:
</BLOCKQUOTE>
<P>
Notice that you don't need to use URL eNCoding because the information
will not be sent through the Internet.
<P>
When you are ready, execute your CGI program from the command
line with a command like this:
<BLOCKQUOTE>
<PRE>
perl -w gestbook.pl < input.dat
</PRE>
</BLOCKQUOTE>
<P>
To summarize the debugging process follows these steps:
<OL>
<LI>Create a DOS batch or UNIX script file to initialize the environment
variables that your CGI program will use.
<LI>Create a test file that contains the form information. Use
an <TT>&</TT> character between
<TT>name=value</TT> fields.
<LI>Execute your CGI script using file redirection to use the
test file as <TT>STDIN</TT>.
<LI>Fix any errors that arise.
</OL>
<H2><A NAME="CreatingaGuestbookforYourSite"><FONT SIZE=5 COLOR=#FF0000>
Creating a Guestbook for Your Site</FONT></A></H2>
<P>
In this section, you create a Guest book for your web site. A
Guest book gives visitors a place to add comments and see what
comments other visitors have made. I find that they add to the
sense of community that a Web site has.
<P>
The sample Guestbook application will be presented in two stages.
First, an HTML form is used to request information, then the information
is saved and all the Guest book entries are displayed by a CGI
program. Second, the CGI program is enhaNCed with better error
handling and some new features. Figure 20.1 shows what the finished
Guestbook will look like.
<P>
<A HREF="f20-1.gif" tppabs="http://cheminf.nankai.edu.cn/~eb~/Perl%205%20By%20Example/f20-1.gif"><B>Figure 20.1 : </B><I>The finished Guestbook</I>.</A>
<H3><A NAME="TheBasicGuestbook">
The Basic Guestbook</A></H3>
<P>
Typically a Guestbook application is reached from a Web site's
home page. You might want to add a link like the following to
your home page:
<BLOCKQUOTE>
<PRE>
<A HREF="addgest.htm">[Guestbook]</A>
</PRE>
</BLOCKQUOTE>
<P>
Then place the web page in Listing 20.4 into the virtual root
directory of your Web server. Clicking the hypertext link will
bring visitors to the Add Entry form.
<P>
<IMG SRC="pseudo.gif" tppabs="http://cheminf.nankai.edu.cn/~eb~/Perl%205%20By%20Example/pseudo.gif" BORDER=1 ALIGN=RIGHT><p>
<BLOCKQUOTE>
<I>Start the HTML web page.<BR>
Define the web page header which holds the title.<BR>
Start the body of the page.<BR>
Display a header.<BR>
Display some instructions.<BR>
Start a HTML form.<BR>
Start a HTML table.<BR>
Each row of the table is another input field.<BR>
Define the submit button.<BR>
End the table.<BR>
End the Form<BR>
End the body of the page.<BR>
End the page.</I>
</BLOCKQUOTE>
<HR>
<BLOCKQUOTE>
<B>Listing 20.4 ADDGEST.htm-The Add Entry to Guestbook
HTML Form<BR>
</B>
</BLOCKQUOTE>
<BLOCKQUOTE>
<PRE>
<HTML>
<HEAD><TITLE>Add to our Guestbook</TITLE></HEAD>
<BODY>
<CENTER><H1>Add to our Guestbook</H1></CENTER>
Fill in the blanks below to add to our Guestbook. The only fields that you
have to fill in are the comments and name section. Thanks!
<HR>
<FORM METHOD=POST ACTION="/cgi-bin/gestbook.pl">
<TABLE BORDER=0 CELLPADDING=10>
<TR>
<TD>Your Name:</TD>
<TD><INPUT TYPE=text NAME=name SIZE=30></TD>
</TR>
<TR>
<TD>Email:</TD>
<TD><INPUT TYPE=text NAME=email SIZE=40></TD>
</TR>
<TR>
<TD VALIGN=top>Comments:</TD>
<TD><TEXTAREA NAME=comments COLS=60 ROWS=4></TEXTAREA></TD>
</TR>
</TABLE>
<INPUT TYPE=submit VALUE="Add Entry"> <INPUT TYPE=reset>
</FORM>
</BODY>
</HTML>
</PRE>
</BLOCKQUOTE>
<HR>
<P>
The only thing you might need to change in order for this form
to work is the <TT>ACTION</TT> modifier
in the <TT><FORM></TT> tag.
The directory where you place the CGI program might not be <TT>/cgi-bin</TT>.
The <TT>addgest.htm</TT> file will
generate a Web page that looks like the following figure.
<P>
<A HREF="f20-2.gif" tppabs="http://cheminf.nankai.edu.cn/~eb~/Perl%205%20By%20Example/f20-2.gif"><B>Figure 20.2 : </B><I>The Add Entry Form</I>.</A>
<P>
The CGI program in Listing 20.5 is invoked when a visitor clicks
on the submit button of the Add Entry HTML form. This program
will process the form information, save it to a data file and
then create a web page to display all of the entries in the data
file.
<P>
<IMG SRC="pseudo.gif" tppabs="http://cheminf.nankai.edu.cn/~eb~/Perl%205%20By%20Example/pseudo.gif" BORDER=1 ALIGN=RIGHT><p>
<BLOCKQUOTE>
<I>Turn on the warning option.<BR>
Turn on the strict pragma.<BR>
Declare a hash variable to hold the HTML form field data.<BR>
Get the local time and pretend that it is one of the form fields.
<BR>
Get the data from the form.<BR>
Save the data into a file.<BR>
Send the HTTP header to the remove web browser.<BR>
Send the start of page and header information.<BR>
Send the heading and request a horizontal line.<BR>
Call the </I><TT><I>readFormData()</I></TT><I>
fuNCtion to display the Guest book entries.<BR>
End the web page.<BR>
Define the </I><TT><I>getFormData()</I></TT><I>
fuNCtion.<BR>
Declare a local variable to hold the refereNCe to the input field
hash.<BR>
Initialize a buffer.<BR>
If the </I><TT><I>GET</I></TT><I>
method is used, copy the form information into the buffer.<BR>
If the </I><TT><I>POST</I></TT><I>
method is used, read the form information into the buffer.<BR>
Iterate over the array returned by the </I><TT><I>split()</I></TT><I>
fuNCtion.<BR>
Decode both the input field name and value.<BR>
Compress multiple </I><TT><I><P></I></TT><I>
tags into one.<BR>
Convert </I><TT><I><</I></TT><I>
into </I><TT><I>&lt;</I></TT><I>
and </I><TT><I>></I></TT><I> into
</I><TT><I>&gt;</I></TT><I> stopping
HTML tags from interpretation.<BR>
Turn back on the bold and italic HTML tags.<BR>
Remove unneded carriage returns.<BR>
Convert two newlines into a HTML paragraph tag.<BR>
Convert single newlines into spaces.<BR>
Create an entry in the input field hash variable.<BR>
Define the </I><TT><I>decodeURL()</I></TT><I>
fuNCtion.<BR>
Get the eNCoded string from the parameter array.<BR>
Translate all plus signs into spaces.<BR>
Convert character coded as hexadecimal digits into regular characters.
<BR>
Return the decoded string.<BR>
Define the </I><TT><I>zeroFill()</I></TT><I>
fuNCtion-turns "1" into "01".<BR>
Declare a local variable to hold the number to be filled.<BR>
Declare a local variable to hold the string length that is needed.
<BR>
Find differeNCe between current string length and needed length.
<BR>
If the string is big enough (like "12") then return
it.<BR>
If the string is too big, prefix it with some zeroes.<BR>
Define the </I><TT><I>saveFormData()</I></TT><I>
fuNCtion.<BR>
Declare two local variables to hold the hash and file name.<BR>
Open the file for appending.<BR>
Store the contents of the hash in the data file.<BR>
Close the file.<BR>
Define the </I><TT><I>readFormData()</I></TT><I>
fuNCtion.<BR>
Declare a local variable to hold the file name.<BR>
Open the file for reading.<BR>
Iterate over the lines of the file.<BR>
Split the line into four variables using ~ as demlimiter.<BR>
Print the Guest book entry using a minimal amount of HTML tags.
<BR>
Use a horizontal rule to separate entries.<BR>
Close the file.</I>
</BLOCKQUOTE>
<HR>
<BLOCKQUOTE>
<B>Listing 20.5 20LST05.PL-A CGI Program to Add a Guestbook
Entry and Display a Guestbook HTML Page<BR>
</B>
</BLOCKQUOTE>
<BLOCKQUOTE>
<PRE>
#! /user/bin/perl -w
use strict;
my(%fields);
my($sec, $min, $hour, $mday, $mon, $year) = (localtime(time))[0..5];
my($dataFile) = "data/gestbook.dat";
$mon = zeroFill($mon, 2);
$hour = zeroFill($hour, 2);
$min = zeroFill($min, 2);
$sec = zeroFill($sec, 2);
$fields{'timestamp'} = "$mon/$mday/$year, $hour:$min:sec";
getFormData(\%fields);
saveFormData(\%fields, $dataFile);
print("Content-type: text/html\n\n");
print("<HTML>\n");
print("<HEAD><TITLE>Guestbook</TITLE></HEAD>\n");
print("<H1>Guestbook</H1>\n");
print("<HR>\n");
readFormData($dataFile);
print("</BODY>\n");
print("</HTML>\n");
sub getFormData {
my($hashRef) = shift;
my($buffer) = "";
if ($ENV{'REQUEST_METHOD'} eq "GET") {
$buffer = $ENV{'QUERY_STRING'};
}
else {
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
}
foreach (split(/&/, $buffer)) {
my($key, $value) = split(/=/, $_);
$key = decodeURL($key);
$value = decodeURL($value);
$value =~ s/(<P>\s*)+/<P>/g; # compress multiple <P> tags.
$value =~ s/</&lt;/g; # turn off all HTML tags.
$value =~ s/>/&gt;/g;
$value =~ s/&lt;b&gt;/<b>/ig; # turn on the bold tag.
$value =~ s!&lt;/b&gt;!</b>!ig;
$value =~ s/&lt;i&gt;/<b>/ig; # turn on the italic tag.
$value =~ s!&lt;/i&gt;!</b>!ig;
$value =~ s!\cM!!g; # Remove unneeded carriage re
$value =~ s!\n\n!<P>!g; # Convert 2 newlines into para
$value =~ s!\n! !g; # convert newline into space.
%{$hashRef}->{$key} = $value;
}
$fields{'comments'} =~ s!\cM!!g;
$fields{'comments'} =~ s!\n\n!<P>!g;
$fields{'comments'} =~ s!\n!<BR>!g;
}
sub decodeURL {
$_ = shift;
tr/+/ /;
s/%(..)/pack('c', hex($1))/eg;
return($_);
}
sub zeroFill {
my($temp) = shift;
my($len) = shift;
my($diff) = $len - length($temp);
return($temp) if $diff <= 0;
return(('0' x $diff) . $temp);
}
sub saveFormData {
my($hashRef) = shift;
my($file) = shift;
open(FILE, ">>$file") or die("Unable to open Guestbook data file.");
print FILE ("$hashRef->{'timestamp'}~");
print FILE ("$hashRef->{'name'}~");
print FILE ("$hashRef->{'email'}~");
print FILE ("$hashRef->{'comments'}");
print FILE ("\n");
close(FILE);
}
sub readFormData {
my($file) = shift;
open(FILE, "<$file") or die("Unable to open Guestbook data file.");
while (<FILE>) {
my($timestamp, $name, $email, $comments) = split(/~/, $_);
print("$timestamp: <B>$name</B> <A HREF=mailto:$email>$email</A>\n");
print("<OL><I>$comments</I></OL>\n");
print("<HR>\n");
}
close(FILE);
}
</PRE>
</BLOCKQUOTE>
<HR>
<P>
This program introduces no new Perl tricks so you should be able
to easily understand it. When the program is invoked, it will
read the form information and then save the information to the
end of a data file. After the information is saved, the program
will generate an HTML page to display all of the entries in the
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -