Home : Internet : Perl : Form Data

How to Use a Form Data in Perl

This page shows how to send information from a web page form to a perl script.

The Form

Create a standard HTML form with the input values you wish to pass to the script. For example:

<form name="myForm" method="post" action="myScript.cgi">
<input type="text" name="textfield">
<input type="hidden" name="hiddenfield" value="Secret Text">
<input type="submit" name="subbtn" value="Submit">
</form>

The Script Code

In the perl script, use a block of code like the one below to extract the form data. The comments are included to show you what is happening - you can safely remove them.

# Read the standard input (sent by the form):
read(STDIN, $FormData, $ENV{'CONTENT_LENGTH'});
# Get the name and value for each form input:
@pairs = split(/&/, $FormData);
# Then for each name/value pair....
foreach $pair (@pairs) {
	# Separate the name and value:
	($name, $value) = split(/=/, $pair);
	# Convert + signs to spaces:
	$value =~ tr/+/ /;
	# Convert hex pairs (%HH) to ASCII characters:
	$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
	# Store values in a hash called %FORM:
	$FORM{$name} = $value;
}

The form's input values can now be used with a key like so: $FORM{'inputname'} , where 'inputname' is the name of the form input item. For example:

print "The following text was entered in the e text field: $FORM{'textfield'}";
print "The hidden text is: $FORM{'hiddenfield'}";