| ACADEMIC COMPUTING and COMMUNICATIONS CENTER | ||||||||
| |||||||||||||||||||||
CGI | |||||||||||||||||||||
| Forms and Scripts | |||||||||||||||||||||
|
A CGI script is just a program invoked by a web server when an appropriate URL is requested. Arguments are passed (usually, but not necessarily, from a web form) and put into the environment. The script then computes a response (usually, but not necessarily, an html page) and returns it to the user. Some issues:
You probably already know that you can run CGI scripts at UIC by using perlwrap. |
|||||||||||||||||||||
| Environment Variables | |||||||||||||||||||||
|
One type of input comes from the web server, and is placed in the environment, accessible via the pseudo-hash %ENV. All you need to know is what's available. I usually check NCSA for a complete list, but here are some favorites:
|
|||||||||||||||||||||
| Parameter Passing | |||||||||||||||||||||
|
The second class of input, that from the browser request, depends on the method, GET or POST. Also, this input is encoded by one of several methods. Fortunately, there are libraries, such as CGI.pm, that do all the dirty work. So all you need do is call the library to get what you need. |
|||||||||||||||||||||
| Output | |||||||||||||||||||||
|
Whatever you send to STDOUT will be sent back to the browser. So simply compute your response and print it. But you must send it in this format:
print "Content-type: text/html\n\n";
print "<html><head><title>Environment</title></head>\n";
print "<body>\n<h1>Env</h1>\n<table>\n";
foreach (keys %ENV) {
print "<tr><td>$_</td><td>$ENV{$_}</td></tr>\n";
}
print "</table>\n</body>\n</html>\n";
|
|||||||||||||||||||||
| CGI.pm | |||||||||||||||||||||
|
CGI.pm is a rather extensive library. It not only parses incoming parameters, but it helps build the output, can save state to disk, can run from the web or command line, and probably more. Details from perldoc CGI. Personally, I don't want so much service, but I use it for two purposes:
Here's an example of how to get the value of what the user typed into the input box named "textin".
use CGI;
$input = new CGI;
$textin = $input->param('textin');
|
|||||||||||||||||||||
| Debugging | |||||||||||||||||||||
|
Using CGI.pm and running the script from the command line is one nice way of finding errors. But sometimes you just have to run the script through the web server. In this case, consider changing the URL to use perlwrap-d instead of perlwrap. (Or use perlwrap-auth-d instead of perlwrap-auth if you are using authentication.) The -d option will print STDERR and STDOUT back to the browser, as well as give you various information from the startup of perlwrap. Getting STDERR this way can be invaluable, particularly if the script dies because of perl errors, before it invokes any of your debugging print statements. Check the bottom of the output for clues. |
|||||||||||||||||||||
| Perl II | Previous: 7. Typeglobs | Next: 9. Security |
| 1999-3-3 BobG |
|