Reading and Parsing Form Data with cgi-lib.pl
sub ReadParse { // Assign the incoming associative // array to the %in array if there // is one. Otherwise, we will use // the %in name. Also, prepare some // local variables. Since this // array is passed by reference, we // will be filling the array for use // by the calling program. local (*in) = @_ if @_; local ($i, $key, $val); // Test to see if the data is POST // or GET data and handle it in // either case. Remember from // yesterday? if ($ENV{'REQUEST_METHOD'} eq "GET") { $in = $ENV{'QUERY_STRING'}; } elsif ($ENV{'REQUEST_METHOD'} eq "POST") { read(STDIN, $in, $ENV{'CONTENT_LENGTH'}); } // Create an array of name/value pairs // by splitting the encoded data on the // ampersand sign. @in = split(/[&;]/,$in); // Now, for each name/value pair, // we will... // // 1. Substitute plus signs for spaces // 2. Split each name/value pair into // a name and a value. // 3. Decode the encoded data for names // and values. remember, everything // has been encoded. // 4. Handle multiple select values. // 5. Add the name/value pair as // elements in an associative array foreach $i (0 .. $#in) { $in[$i] =~ s/\+/ /g; ($key, $val) = split (/=/,$in[$i],2); $key =~ s/%(..)/pack("c", hex($1))/ge; $val =~ s/%(..)/pack("c", hex($1))/ge; $in{$key} .= "\0" if (defined($in{$key})); $in{$key} .= $val; } // Now return the number of elements in // the associative array. return scalar (@in); } #!/usr/local/bin/perl require "cgi-lib.pl"; &ReadParse(*form_data); print "Content-type: text/html\n\n"; print qq! <HTML> <HEAD> <TITLE>Testing Form Input</TITLE> </HEAD> <BODY> <TABLE>!; foreach $key (keys(%form_data)) { print qq! <TR> <TD>$key</TD> <TD>$form_data{$key}</TD> </TR>!; } print qq! </TABLE> </BODY> </HTML>!;
Additional Resources:![]() Table of Contents Building a Form Processor ![]() |
Hosted by Graphics & Media Lab
http://graphics.cs.msu.su |
![]() |
mailto: Laboratory |