Transcript Document 7186381
CGI with Perl
Darby Tien-Hao Chang (a.k.a. dirty) Department of Electrical Engineering, National Cheng Kung University
A typical Perl CGI session goes something like this:
hello.pl
#!/usr/bin/perl print "Content-type: text/html\r\n\r\n"; print "\n"; print "
Hello World!
\n"; print "\n"; print "\n"; exit (0);Anatomy of a CGI program
A CGI program always has 3 basic parts: MIME type HTML document Return value
MIME type
Content-type: text/html
HTML document
You know that
Return value
After a CGI program ends, the web server collects the "return value" of the program so that it knows if there was an error or not This is sometimes useful for debugging purposes because the programmer is allowed to determine the meaning of non-zero return values In Perl, you can specify what the return value of the CGI program is with the exit keyword: exit (0); # normal exit code exit (1): # something bad happened Change the return value in your hello.pl to a '1' and see if you can find the resulting error code in your web server's error log.
Let
’
s see the log of your httpd
hello.pl with CGI.pm
#!/usr/bin/perl # It's always a good idea to use the strict pragma while developing # Perl code, it makes Perl warn about dangerous code use strict; # We're also going to include the CGI module, so that we can take # advantage of other programmer's efforts (One of Larry Wall's basic # tennants is that programmers are fundamentally lazy -- he's probably # right, but I can't be bothered to prove it right now) use CGI; # instantiate a new CGI object my $cgi = new CGI; # perform a single print statement, with liberal use of the perl # string concatenator "." and some CGI methods print $cgi->header . $cgi->start_html('Hello World!') .
$cgi->h1('Hello World!') . $cgi->end_html; # Tell the webserver everything is fine exit (0);
Where is my CGI.pm?
Hey, TA
About HTML forms
An HTML
tag can contain Where each element has aname
and an associated
value
.
The value may be included with the tag itself (see the radio and hidden examples above), and/or it can be supplied by the user.
Names
Variable names can be any legal HTML identifier and are almost always supplied via the
name
property of an HTML tag: Once the form above is sent to the web server, the CGI program will be able to access these elements by those names: my $foo = $cgi->param('foo'); my $bar = $cgi->param('bar'); my $hair_index = $cgi->param('Desired Hair Color'); my $date = new Date($cgi->param('Date')); my $name = $cgi->param('First Name');
Values
A value can either be a string (as shown above), or it can be an array of items How do you access the variables in the case that you have a series of checkboxes?
my @values = $cgi->param('listOfStuff');
POST and GET
Let's take a closer look at the