5-2 CGI ?數?傳????

W`ФF CGI 򥻥\PzA`N CGI pѨϥΪ̨oTC

ڭ̥H@²檺d (widget0.htm) ӻG

Example]widget0.htm^G

dҥ]tF@ӫ²檺AlXpUG

lɡ]widget0.htm^G]ǦϰUYi^
<html>
<head>
<META HTTP-EQUIV="Content-Type" CONTENT="text/html; charset=big5">
<TITLE>A Simple Form for CGI Programming</TITLE>
</head>

<body background="/jang/graphics/background/paper.jpg">
<h2 align=center>A Simple Form for CGI Programming</h2>
<hr>

<form method=get action="getCgiParam.pl">
<ul>
<li>jWG<input name="your_name" value="Roger Jordan & j">
<li>ʧOG<input type="radio" name="gender" value="male">k
	<input type="radio" name="gender" value="female">k
	<input type="radio" name="gender" value="unknown" checked>Tw
</ul>
<input type="submit">
<input type="reset">
</form>
<hr>
<body>
</html>

ѤWzlXiݥXATǰekO get]o]O檺 method ʽ誺w]ȡ^AϥΪ̫UueXdߡvɡAƧYѦAݪ getCgiParam.pl ӳBzA^ǵGpUG

ѤWz^ǪAiݥX}OugetCgiParam.pl?your_name=Roger+Jang&gender=unknownvAN檺TO[bBz{᭱AA@_eAAoNO method get ɪ@kCAo@TA|NxsbW٬ QUERY_STRING ܼơAMAe~{]b getCgiParam.pl^iBzCgetCgiParam.pl lXpUG

lɡ]getCgiParam.pl^G]ǦϰUYi^
if ($ENV{"QUERY_STRING"} ne "") {
	$paramStr = $ENV{"QUERY_STRING"};			# method=get
	$method = "get";
} else {
	read(STDIN, $paramStr, $ENV{'CONTENT_LENGTH'});	# method=post
	$method = "post";
}

%FORM = &parseForm($paramStr);

print "Content-type: text/html\n\n";
@allkeys = sort keys %FORM;

print "<html><head><title>Form Elements</title><meta HTTP-EQUIV=\"Content-Type\" CONTENT=\"text/html; charset=big5\"></head>\n";
print "<body>\n";
print "<h2 align=center>CGI pǻΩѼơ]method=get^</h2>\n";
print "<hr>\n";
print "<h3>ѼƶǻkG</h3>";
print "<blockquote><font color=green>$method</font></blockquote>\n";
print "<h3>CGI 쪺rG</h3>";
print "<blockquote><font color=green>$paramStr</font></blockquote>\n";
print "<h3>XӪTG</h3>";
print "<blockquote>\n";
for $key (@allkeys) {
	print "\$FORM(\"$key\") = <font color=green>$FORM{$key}</font><br>\n";
}
print "</blockquote></body></html>\n";

# Split the name-value pairs of a CGI parameter string
sub parseForm {
	my($parameter_string) = @_;
	my(%FORM);
	@pairs = split(/&/, $parameter_string);			# ھ "&" N name-value pairs Ѷ}
	foreach $pair (@pairs) {				# C@ name-value pair iBz
		($name, $value) = split(/=/, $pair);			# X name M value
		$value =~ tr/+/ /;				# N "+" Nť
		$value =~ s/%([a-fA-F0-9][a-fA-F0-9])/chr(hex($1))/eg;	# N %-encoding Ѧ^r
		$FORM{$name} .= "#" if defined($FORM{$name});	# YƪAH "#" s
		$FORM{$name} .= $value;			# NGxsb FORM ܼ
	}
	return(%FORM);
}

bWzlXAڭ̥[F\hѡAHPA Perl pѰeiӪrC

ƹWAWz{XiPɥΩ method=get M method=post رpCUoӽdҡ]widget.htm^ANOΦP˪ CGI {Ӳqѥ method=post ҰeiӪrG

Example]widget.htm^G

dҥ]tFҦ`Ψ쪺椸AϥΪ̫UueXdߡvɡAƧYѦAݪ getCgiParam.pl ӳBzCѩҥΨ쪺ǰekO postA] Perl {gѼзǿJŪJѼƦrArꪺ׫hiܼ CONTENT_LENGTH oCЦUPǦۦոլݦdҡI

HUO get M post oذѼƶǰe覡ӪG

  Method=Get Method=Post
ǰe覡 gܼ QUERY_STRING gѼзǿJ]ץiܼ CONTENT_LENGTH o^
Ū覡 $paramStr = $ENV{"QUERY_STRING"}; read(STDIN, $paramStr, $ENV{'CONTENT_LENGTH'});
uI uʸj r׭eP
I r׭YV uʸp]ɤ]OuI^


Perl