In this article I will discuss how you can get your users information into your CGI script by the use
of forms and in Part 2, the query string.
Now what happens when they press submit?
The information filled in is sent to the script as one long line, with many items exchanged for different
things. i.e. a space ( ) is turned into a plus sign (+).
So the information from the above form when filled in, will give the following to the script-
name=Richard+Livsey&sex=male&eye_colour=blue&Submit=Submit
The information is there, now how to decode it and put it to use.
Below is the code that I use to get the information into a usable form and if you look at most of my
scripts (from www.cache-22.co.uk)
chances are they will have this in them somewhere.
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;
}
Now to explain what it does -
read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'});
This reads the information string and stores it into the variable $buffer.
@pairs = split(/&/,$buffer);
This splits up the buffer string into the array @pairs at the
&. So @pairs will look like
the following -
name=Richard+Livsey
gender=male
eye_colour=blue
Submit=Submit
foreach $pair(@pairs) {
This will go through each line of the @pairs array and do the
following to it -
($name, $value) = split(/=/,$pair);
Split the line at the = and
assign the left side to the variable $name and the right to
$value.
$value =~ tr/+/ /;
This translates a + sign into
a space, one of the things which is changed when the form is submitted.
$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/pack("C", hex($1))/eg;
This changes back other things form nonsense into meaningful symbols.
$FORM{$name} = $value;
}
Then puts the values into the hash %FORM and closes the
foreach loop with the }.
So now we have a hash with all our information in which can be called as we need it. Personally,
I like to turn these hash values into meaningful variables, so for the
information in our hash I will assign them to variables as follows -
$name = $FORM{'name'};
$gender = $FORM{'gender'};
$eye_colour = $FORM{'eye_colour'};
There you go. The information is now in variables that you can use as you please, for example, you could
then print out a page that tells them what they have selected as follows -
print "Your name is $name, you are $sex and you have $eye_colour
eyes.";
This would print out the following for me -
Your name is Richard Livsey, you are male and you have blue eyes.
Simple, but it is only the beginning of what you can do with the information once you have it in
your script.
Now to find out about the query string in part 2.