How To access GET / POST request data using Perl

This article describes how to access data from an HTTP GET / POST Web request using Perl.  

While there are many Perl modules available (including the CPAN) which
already contain such functionality, the following code demonstrates
how to pull data from both an HTTP GET and HTTP POST request without
any external dependencies.

sub populateQueryFields {
%queryString = ();
my $tmpStr = $ENV{ "QUERY_STRING" };
@parts = split( /\&/, $tmpStr );
foreach $part (@parts) {
( $name, $value ) = split( /\=/, $part );
$queryString{ "$name" } = $value;
}
}

sub populatePostFields {
%postFields = ();
read( STDIN, $tmpStr, $ENV{ "CONTENT_LENGTH" } );
@parts = split( /\&/, $tmpStr );
foreach $part (@parts) {
( $name, $value ) = split( /\=/, $part );
$value =~ ( s/%23/\#/g );
$value =~ ( s/%2F/\//g );
$postFields{ "$name" } = $value;
}
}

populateQueryFields pulls all name/value pairs from a URL (GET
request) into a hash called %queryString. populatePostFields
pulls all data from a POST request (via STDIN) into a hash called
%postFields. Examples:

Given the following URL,


http://www.mydomain.com/cgi-bin/script.pl?fname=Jason&lname=Plackey

&populateQueryFields;
$firstName = $queryString{ "fname" };
$lastName = $queryString{ "lname" };

Would pull "Jason" and "Plackey" into $firstName and $lastName,
respectively.

Similarly, given an HTML form->POST request,
...
<FORM ACTION="../cgi-bin/script.pl" METHOD="POST">
<INPUT TYPE="TEXT" NAME="fname">
<INPUT TYPE="TEXT" NAME="lname">
...
</FORM>

&populatePostFields;
$firstName = $postFields{ "fname" };
$lastName = $postFields{ "lname" };

Would, once again, pull the respective data entered via the HTML
form into the $firstName and $lastName fields.

One additional note: In the populatePostFields routine, there are
two calls to s///. These are optional, and mimic (lightly) the
functionality of an unEscape() or urlDecode() type of procedure. The
specific two calls made in the routine above replace "%23" with a
pound (#) sign, and "%2F" with a forward slash (/). These can be
altered as you see fit.

Enjoy,

Jason Plackey
Vice President of Business Development
Raven2K Integrated Solutions
http://www.raven2k.com
jplackey@raven2k.com

 

Share this article!

Follow us!

Find more helpful articles: