This document was written by CS 290W TA David Corcoran and was last modified
http://icdweb.cc.purdue.edu/~bxd/guest.cgi?FIRSTNAME=Timothy&LASTNAME=JamesThe Web server dumps all the information after the Question Mark (?) into an environmental variable called QUERY_STRING.
<INPUT TYPE=TEXT SIZE=20 NAME=FIRSTNAME> <INPUT TYPE=TEXT SIZE=20 NAME=LASTNAME>FIRSTNAME is the NAME or Key in that textfield. Whatever is placed in that textfield will be the Value that is passed in the QUERY_STRING when the submit button is pressed. If the name "Timothy" was placed in the first textfield, "James" put in the second and the submit button was pressed, your QUERY_STRING would look like the following:
FIRSTNAME=Timothy&LASTNAME=James
# Retrieving information using POST #!/usr/local/bin/perl $iSizeOfInfo = $ENV{'CONTENT_LENGTH'}; read(STDIN, $sTheString, $iSizeOfInfo);Here we are using the read() command to get METHOD=POST data from STDIN.
# Retrieving Information using GET #!/usr/local/bin/perl $sQuery_string = $ENV{'QUERY_STRING'}; @asKeyPairs = split(/&/, $sQuery_string);You can do something similar with POSTed data:
# Retrieving Information using POST #!/usr/local/bin/perl $iSizeOfInfo = $ENV{'CONTENT_LENGTH'}; read(STDIN, $sTheString, $iSizeOfInfo); @asKeyPairs = split(/&/, $sTheString);In either case this will give you the array @asKeyPairs which will contain two key/value pairs: $asKeyPairs[0] which is FIRSTNAME=Timothy and $asKeyPairs[1] which is LASTNAME=James. By using a loop you can then split up each of those values using the equals sign as the delimiter. To do this easily, though, Perl offers another data type called an associative array.
$asPeople{"FIRSTNAME"} = "Timothy"; $asPeople{"LASTNAME"} = "James"; $asPeople{"MIDDLE"} = "R."; $asPeople{"PHONE"} = "497-8394"; KEY VALUE ---------------------- FIRSTNAME Timothy LASTNAME James MIDDLE R. PHONE 497-8394Associative arrays allow you to store two values -- a key and its associated value. If you asked what FIRSTNAME was, it would return Timothy. LASTNAME would return James. Getting values out of associative arrays is just as easy:
#!/usr/local/bin/perl $sFirstname = $asPeople{"FIRSTNAME"}; # Notice the following. $sFirstname = $in{"FIRSTNAME"};Both should be quite straight forward. Notice the second though. Does it look familiar? It should, because cgi-lib.pl stores its Key/Values from the QUERY_STRING into an associative array called $in. When you use the statement $sName = $in{"FIRST"}; you are merely querying an associative array.
There are a few other things that cgi-lib.pl does also. For example, special characters; cgi-lib.pl recognizes escaped characters such as the ampersand and deals with them appropriately. Also, if FIRSTNAME was actually two words such as Dr. Timothy, QUERY_STRING represents these spaces as + (plus) signs. Cgi-lib.pl replaces the + signs with blanks.