#!/local/bin/perl
# a perl script to handle both GET and POST methods
# get the type of method that was used by the
# user to issue this request
$request_method = $ENV{'REQUEST_METHOD'};
# if the GET method was used
if ($request_method eq "GET") {
# get the query request from the environment variable
$query = $ENV{'QUERY_STRING'};
# if the POST method was used
} elsif ($request_method eq "POST") {
# get the query request from the standard input
# first we get the size of the query request (# of chars)
$query_size = $ENV{'CONTENT_LENGTH'};
# then we read from STDIN that many number of chars
read (STDIN, $query, $query_size);
# otherwise, we got an invalid request
} else {
print "Content-type: text/html", "\n";
print "Status: 500 Server Error", "\n\n";
print "
Server Error", "\n";
print "Server Error
", "\n";
print "
Unsuported request method
", "\n";
exit;
}
# now we have the query string, let's constrcut a hash table from it
# where keys are the keys in the query string, values are the corresponding values
%query_data = ();
# first we separat each key value pairs
@key_values = split (/&/, $query);
# for each key value pair ...
foreach $key_value (@key_values) {
($key, $value) = split (/=/, $key_value);
# replace + with a space
$value =~ tr/+/ /;
# the regular expression matches any hexadecimal value
# and store it in the variable $1
# the pack and hex operator convert the value in $1 to an ASCII equivalent
# e means the second argument as an expression
$value =~ s/%([\dA-Fa-f][\dA-Fa-f])/pack ("C", hex ($1))/eg;
# insert the key value pair into the query hash
# we need to consider multiple values (select element with "multiple" turned on)
# if the key value pair already exist in the hash
if (defined($query_data{$key})) {
# we append the new value to the old ones
$query_data{$key} = join (", ", $query_data{$key}, $value);
} else {
# otherwise, just add a new entry in the hash
$query_data{$key} = $value;
}
}
# output the result
print "Content-type: text/html", "\n\n";
print "", "\n";
print "GET and POST Example", "\n";
print "";
# depends on the query string, the output is different
if ($query_data{'show_data'} eq 'yes') {
print "Thanks for your submission!
", "\n";
print "Here is the form data you submitted
", "\n";
print "
", "\n";
foreach $key (keys(%query_data)) {
print "", $key, ": ", $query_data{$key}, "
\n";
}
print "
", "\n";
} else {
print "Thanks for your submission!
", "\n";
}
print "", "\n";