PERL CGI Tutorial
for Writing Interactive Form Scripts

Parsing an HTML Form

Send the Form to the Browser

To demonstrate the code from the first lesson we'll use it to send a simple HTML form to the browser. If this is your first experience with HTML forms you may want to read the lessons on Forms in the HTML tutorial before starting.

form.pl

#!/usr/bin/perl
print "Content-type:text/html\n\n";

print "<html>\n";
print "<head><title>Sample Form</title></head>\n";
print "<body>\n";
print "<form method=POST action=parse_form.pl>\n";
print "<pre>\n";
print "Enter First Name:<input type=text name=first size=20>\n";
print "Enter Last Name:<input type=text name=last size=20>\n";
print "<input type=submit value=Submit><input type=reset>\n";
print "</pre>\n";
print "</form>\n";
print "</body>\n";
print "</html>\n";


Try the script

Parse the Form

The action statement in the form above specifies a script named parse_form.pl. This CGI script will convert the information received from the form into usable data and send it to the browser in the form of an HTML page.

Parsing is simply taking the information received from a form and converting it back to usable a form.

The first block of code is fairly universal. You can use it to parse just about any form using the POST method. The last 2 lines would be changed to coincide with the input box names on the form.

parse_form.pl

#!/usr/bin/perl
read(STDIN, $buffer,$ENV{'CONTENT_LENGTH'});
$buffer =~ tr/+/ /;
$buffer =~ s/\r/ /g;
$buffer =~ s/\n/ /g;
$buffer =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C",hex($1))/eg;
$buffer =~ s/<!--(.|\n)*-->/ /g;
$buffer =~ tr/\\|[|]|<|!|"|$|{|}|*|#|'|>|||;|%/ /;

@pairs = split(/&/,$buffer);
foreach $pair(@pairs){
($key,$value)=split(/=/,$pair);
$formdata{$key}.="$value";
}
$first=$formdata{'first'};
$last=$formdata{'last'};


print "Content-type:text/html\n\n";

print "<html>\n";
print "<head><title>Sample Response</title></head>\n";
print "<body>\n";
print "<p>Thank you: $first $last</p>\n";
print "</body>\n";
print "</html>\n";

Helpful Information

Windows users: Copy the code for each script and paste it into Notepad. Use the Saveas function to save the scripts with a .pl extension. Upload them to your cgi-bin folder and use the Chmod function to change the permissions for each script to 755.

Run the form.pl script from your browser by typing yourdomain/cgi-bin/form.pl

Send to Browser Save to File
CGI Online is a service provided by Net Success 2000 Plus Inc.
PO Box 1508
Somerset, KY 42502
Last Modified: January 20, 2008

| HTML TOC | Website Design Workshop | Home |