|
Common Gateway Interface (CGI)
Part:
1
2
(Continued from previous part...)
CGI Query String
Query String: The remaining part of the requesting URL string
immediately after the "?". Query strings are usually used to pass a list
of variable and value pairs with "&" as the pair delimiter, and "="
as the variable and value separator.
In order to avoid confusion, some characters are encoded in query strings.
" " is encoded into "+". "+", "&", "=", "%" and other special characters are
encoded into a hex number prefixed with "%".
Here is a CGI program to parse query strings, CgiQuery.pl:
#- CgiQuery.pl
#- Copyright (c) 1996 by Dr. Herong Yang
#
print "Content-Type: text/html\n\n";
print "<html><body>\n";
print "<b>Query String Data:</b><br/>\n";
$query = $ENV{'QUERY_STRING'};
@list = split( /\&/, $query);
foreach (@list) {
($var, $val) = split(/=/);
$val =~ s/\'//g;
$val =~ s/\+/ /g;
$val =~ s/%(\w\w)/sprintf("%c", hex($1))/ge;
print($var, ' = ', $val, "<br/>\n");
}
print "</html></body>\n";
Try it with this URL:
http://localhost/cgi-bin/CgiQuery.pl?Exp=1+%2B+2&Res=3
you will get:
Query String Data:
Exp = 1 + 2
Res = 3
A Simple CGI Application - Calculator.pl
Here is a simple CGI application, Calculator.pl:
#- Calculator.pl
#- Copyright (c) 1996 by Dr. Herong Yang
#
&getValues();
$res = "";
$res = eval($exp) if ($exp);
print "Content-Type: text/html\n\n";
print "<html><body>\n";
print "<b>Calculator:</b><br/>\n";
print "<form action=\"/cgi-bin/Calculator.pl\" methor=\"GET\">\n";
print "<table border=\"0\">\n";
print "<tr><td align=\"right\">Expression:</td>\n";
print "<td><input type=\"text\" name=\"exp\"";
print " value=\"$exp\"/></td></tr>\n";
print "<tr><td align=\"right\">Result:</td>\n";
print "<td>$res</td></tr>\n";
print "<tr><td></td>\n";
print "<td><input type=\"submit\" value=\"Evaluate\"/></td></tr>\n";
print "</table></form>\n";
print "</html></body>\n";
exit;
sub getValues {
$query = $ENV{'QUERY_STRING'};
@list = split( /\&/, $query);
foreach (@list) {
($var, $val) = split(/=/);
$val =~ s/\'//g;
$val =~ s/\+/ /g;
$val =~ s/%(\w\w)/sprintf("%c", hex($1))/ge;
$exp = $val if ($var =~ /exp/);
}
}
Enjoy it.
Part:
1
2
|