Chapter 5: Introducing Perl

The CGI environment


[ Comments ] [ Copyright ] [ Chapter contents ] [ Book contents ]


CGI scripts receive a fair amount of information about their execution environment from the web server. Not all this information is standardized; some servers and some clients pass extra information.

You can examine the contents of the environment of a CGI script by checking the keys to the associative array %ENV. %ENV contains environment variables; their names are the keys to the array. For example, $ENV{'QUERY_STRING'} contains the HTTP query that was passed to a CGI script.

When developing scripts it's often useful to have a simple, dumb CGI script kicking around that prints out your environment. In conjunction with a couple of different browsers, you can work out ways of finding out information about your users. Here's a simple script which doesn't actually read a GET or POST query, but prints out everything it finds in its run-time environment (using a neatly formatted table):

#!/bin/perl
#
#
print "Content-type: text/html\n\n";
print "<HEAD><TITLE>Environment dumper</TITLE></HEAD>\n";
print "<BODY><P>\n";
print "<TABLE BORDER=\"4\">\n";
print "<TR><TD><B>Variable</B><TD><B>Value</B>\n";
foreach (keys (%ENV)) {
    print "<TR><TD>$_<TD>$ENV{$_}\n";
}
if ($ENV{'REQUEST_METHOD'} eq "POST") {
    $stdin = <STDIN>;
    print "<TR><TD COLSPAN=\"2\"><B>Uploaded file follows</B> 
    (raw MIME data)\n";
    print "<TR><TD COLSPAN=\"2\">$stdin\n";
}
print "</TABLE>\n</BODY>\n";

exit 0;

It produces output like this:

DIAG?

This tells us a lot about the web browser making the request, even though it doesn't actually parse the query. (Note that if the REQUEST_METHOD variable is set to POST it reads in the query and prints it in a cell in the table without performing any substitutions on it.)

For example, we can see that the HTTP_USER_AGENT (the web browser) is a beta copy of Netscape 2.0; and it's coming from the machine (REMOTE_HOST) fma0.demon.co.uk, at network address 158.152.6.20. The browser is willing to accept the mime types:

If additional information is available, it will show up in this listing; for example, the undigested HTTP query will appear here, as will security information passed using HTACCESS and HTTP_COOKIE data in the HTTP header. (We will cover HTACCESS authorization and cookies later, in the section on servers.)


[ Comments ] [ Copyright ] [ Chapter contents ] [ Book contents ]