Echo Form
This is a basic CGI script for processing Web forms. The script will
take the information from the Web form and print it to the Web browser
in HTML-formatted text.
Open a text editor to write the script:
pico echoform.cgi
Type the following Perl code in your text editor exactly as it appears
here:
#!/usr/local/bin/perl
use CGI;
CGI::ReadParse(*in);
print "Content-type:text/html\n\n";
print '<HTML><HEAD><TITLE>echoform.cgi results</TITLE></HEAD>';
print '<BODY BGCOLOR="FF0066">';
print '<h2>Results of Form Submission with echoform.cgi Script</h2>';
foreach $i (keys %in) {
print "<B>$i = </B> $in{$i}<BR>";
}
print '</BODY></HTML>';
Save the file and exit the editor.
Make the script executable, type:
chmod 755 $HOME/public_html/cgi-bin/echoform.cgi
This table includes a line-by-line explanation of the "echoform.cgi"
CGI script.
#!/usr/local/bin/perl |
Tells the server the Perl interpreter is located in the directory
/usr/local/bin/perl. |
use CGI; |
Loads the CGI module. |
CGI::ReadParse(*in); |
A method from the CGI
module that takes the form field information and saves it as the
hash %in.
The formfield names are the keys of the hash. |
print "Content-type:text/html\n\n";
|
Is a print statement for the HTTP
header. In this case, the header tells the Web browser to display
HTML-formatted text. Double
quotes are required in order to create two newline
characters with "\n\n". |
print '<HTML><HEAD><TITLE>echoform.cgi
results</TITLE></HEAD>';
print '<BODY BGCOLOR="FF0066">';
print '<h2>Results of Form Submission with echoform.cgi Script</h2>'; |
These print statements start the HTML document, create the <HEAD>
section, and begin the <BODY> section of the HTML page. |
foreach $i (keys %in) {
print "<B>$i = </B>
$in{$i}<BR>";
} |
Is called a foreach
loop. In this foreach loop, the commands between the curly braces
{} are repeated once for each key of the hash
%in.
For the first iteration of the loop, the variable
$i evaluates to be the first key in the hash %in.
The variable $in{$i} evaluates to be the value of the hash
at first key $i.
Double quotes
are used so the variables are interpolated. If single quotes were
to be used, this loop would print "$i = $in{$in}" rather
than printing the appropriate values from the form. |
| print '</BODY></HTML>'; |
This print statement closes the HTML document. |
|