📄 ch20.htm
字号:
<P>Then place the web page in Listing 20.4 into the virtual rootdirectory of your Web server. Clicking the hypertext link willbring visitors to the Add Entry form.<P><IMG SRC="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 GuestbookHTML 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 formto work is the <TT>ACTION</TT> modifierin 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 willgenerate a Web page that looks like the following figure.<P><A HREF="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 clickson the submit button of the Add Entry HTML form. This programwill process the form information, save it to a data file andthen create a web page to display all of the entries in the datafile.<P><IMG SRC="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 fieldhash.<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> stoppingHTML 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 returnit.<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 GuestbookEntry and Display a Guestbook HTML Page<BR></B></BLOCKQUOTE><BLOCKQUOTE><PRE>#! /user/bin/perl -wuse 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 ableto easily understand it. When the program is invoked, it willread the form information and then save the information to theend of a data file. After the information is saved, the programwill generate an HTML page to display all of the entries in thedata file.<P>While the program in Listing 20.5 works well, there are severalthings that can improve it:<UL><LI>Error Handling-instead of simply dying, the program couldgenerate an error page that indicates the problem.<LI>Field Validation-blank fields should be checked for and warnedagainst.<LI>Guest book display-visitors should be able to see the Guestbook without needing to add an entry.</UL><P>The CGI program in Listing 20.6 implements these new features.If you add <TT>?display</TT> to theURL of the script, the script will simply display the entriesin the data file. If you add <TT>?add</TT>to the URL of the script, it will redirect the client browserto the <TT>addgest.htm</TT> Web page.If no additional information is passed with the URL, the scriptwill assume that it has been invoked from a form and will readthe form information. After saving the information, the Guestbookpage will be displayed.<P>A debugging routine called <TT>printENV()</TT>has been added to this listing. If you have trouble getting thescript to work, you can call the <TT>printENV()</TT>routine in order to display all of the environment variables andany form information that was read. Place the call to <TT>printENV()</TT>right before the <TT></BODY></TT>tag of a Web page. The <TT>displayError()</TT>fuNCtion calls the <TT>printENV()</TT>fuNCtion so that the error can have as much information as possiblewhen a problem arises.<P><IMG SRC="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>Was the program was invoked with added URL information?<BR>if the display command was used, display the Guest book.<BR>if the add command was use, redirect to the Add Entry page.<BR>otherwise display an error page.<BR>If no extra URL information, check for blank fields.<BR>if blank fields, display an error page.<BR>Save the form data.<BR>Display the Guest book. <BR>Exit the program.<BR>Define the </I><TT><I>displayError()</I></TT><I>fuNCtion.<BR>Display an error page with a specified error message.<BR>Define the </I><TT><I>displayPage()</I></TT><I>fuNCtion.<BR>Read all of the entries into a hash.<BR>Display the Guest book.<BR>Define the </I><TT><I>readFormData()</I></TT><I>fuNCtion.<BR>Declare local variables for a file name and a hash refereNCe.<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>Create a hash entry to hold the Guest book information.<BR>Close the file.<BR>
⌨️ 快捷键说明
复制代码
Ctrl + C
搜索代码
Ctrl + F
全屏模式
F11
切换主题
Ctrl + Shift + D
显示快捷键
?
增大字号
Ctrl + =
减小字号
Ctrl + -