Lesson 8 - Form Input/Processing
Forms Processing

In this topic we will discuss the use of html forms with Perl. You will learn how to access the results of a form filled out
on your web site from environment variables. We will not look into topics beyond the scope of this lesson (like learning the
HTML to create forms.)


The POST Method

When a user inputs form data and submits the form via the POST method your web server will interpret that data and pass it to
your CGI script in STDIN. The length of the content is in the invironment variable CONTENT_LENGTH.


Extracting Results

To get the results of your form you can use the standard code included below. This code extracts the form results from STDIN
for you and parses it into a hash called FORM keyed with the name of the form elements with content set to the value the user
filled the feild in with on your web site.

# Standard form parsing routine.
sub parse_form {
read(STDIN, $buffer, $ENV{CONTENT_LENGTH});
@pairs = split(/&/, $buffer);
foreach $pair (@pairs) {
($name, $val) = split(/=/, $pair);
$val =~ tr/+/ /;
$val =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$FORM{$name} = $val;
}
}

Simply insert the above code into your perl script and call "&parse_form();" somewhere in your script. Once that has been
completed you can access any elements in the FORM hash by using the name of the value in the form. If your form has a text
box called "textbox" you could access the value the user entered with "print $FORM{'textbox'};".


Processing Results

The most common use of forms is to email the results to the website developer. The sample project demonstrates this.

Get This Sample

Lesson 9 - File I/O

Home | Lessons | Get Perl | Resources