With the POST method, form data is sent in an input stream from the server to your CGI. To get this data, store it, and decode it, we'll use the following block of code:
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
@pairs = split(/&/, $buffer);
foreach $pair (@pairs) {
($name, $value) = split(/=/, $pair);
$value =~ tr/+/ /;
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
$FORM{$name} = $value;
}
Let's look at each part of this.
First, we read the input stream using this line:
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
The input stream is coming in over STDIN (standard input), and we're using Perl's read function to store the data into the scalar variable $buffer.
You'll also notice the third argument to the read function, which specifies the length of data to be read.
We want to read to the end of the CONTENT_LENGTH, which is set as an environment variable by the server.
Next we split the buffer into an array of pairs:
@pairs = split(/&/, $buffer);
As with the GET method, form data pairs are separated by & signs when they are transmitted, such as fname=joe&lname=smith.
Now we'll use a foreach loop to further splits each pair on the equal signs:
foreach $pair (@pairs) {
($name, $value) = split(/=/, $pair);
The next line translates every "+" sign back to a space:
$value =~ tr/+/ /;
Next is a rather complicated regular expression that substitutes every %HH hex pair back to its equivalent ASCII character, using the pack() function.
The argument "C" in pack("C", hex($1)) tells the pack() function that it will be passed an unsigned char value.
$1 is a variable that matches the whatever is in the first set of parenthesis.
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
Finally, we store the values into a hash called %FORM:
$FORM{$name} = $value;
The keys of %FORM are the form input names themselves. So, for example, if you have three text fields in the form - called name, email-address, and age - you could refer to them in your script by using $FORM{'name'}, $FORM{'email-address'}, and $FORM{'age'}.
This article was originally written by pyroinfernia |