Monday, April 6, 2009

How to Use a Query String in Perl

A query string is the part of a URL which is attached to the end, after the file name. It begins with a question mark and usually includes information in pairs. The format is parameter=value, as in the following example:

www.mediacollege.com/cgi-bin/myscript.cgi?topic=intro

Query strings can contain multiple sets of parameters, separated by an ampersand (&) like so:

www.mediacollege.com/cgi-bin/myscript.cgi?topic=intro&heading=1

The idea is that the information contained in the query string can be accessed and interpreted by a script. Specifically, the query string data is contained in the variable $ENV{'QUERY_STRING'}.
To Access the Query String Data

You can use a block of code like the one below to access and organise the query string:

if (length ($ENV{'QUERY_STRING'}) > 0){
$buffer = $ENV{'QUERY_STRING'};
@pairs = split(/&/, $buffer);
foreach $pair (@pairs){
($name, $value) = split(/=/, $pair);
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$in{$name} = $value;
}
}

This code will create a hash called $in, from which you can call specific variables like so:

$topic = $in{'topic'};
$heading = $in{'heading'};

Sample code:
#!/usr/bin/perl

# Whether the method used is GET or POST, store the parameters passed in $QueryString
if($ENV{'REQUEST_METHOD'} eq "POST") {
read(STDIN, $QueryString, $ENV{'CONTENT_LENGTH'});
} else {
$type = "display_form";
$QueryString = $ENV{QUERY_STRING};
}

# split the QueryString at &'s to give you a list with each element with a format like "name=value"
@NameValuePairs = split (/&/, $QueryString);

# Split each NameValue pair, replace +'s by spaces, get the character equivalent of any data in hex (%XX) and finally, store it in an associative array
foreach $NameValue (@NameValuePairs) {
($Name, $Value) = split (/=/, $NameValue);
$Value =~ tr/+/ /;
$Value =~ s/%([\dA-Fa-f][\dA-Fa-f])/ pack ("C",hex ($1))/eg;
$in{$Name} = $Value;
$color =$in{'color'};
$name =$in{'name'};
}

print "Content-type: text/html", "\n\n";
HTML CODE HERE

No comments:

Post a Comment