Environment variables

In Perl, there is a special variable called %ENV which contains all the environment variables which are set.

When a web server runs a CGI program, certain environment variables are set to provide information about the web server, the request made by the user agent, and other pertinent information.

Examples of environment variables available to your CGI script include HTTP_USER_AGENT which describes the user agent or browser used to make the request, and HTTP_REFERER, which indicates the referring page (if any).

Exercises

  1. Modify your table-printing script from the previous exercise to print out the hash %ENV.

  2. The HTTP_USER_AGENT environment variable contains the type of browser used to request the CGI script.

    • Write a script which prints out the user agent string for the requesting browser

    • Take a look at what various browsers report themselves as -- try Netscape, Internet Explorer, or Lynx from the Unix command line. You will note that Microsoft browsers purport to be "Mozilla compatible" (i.e. compatible with Netscape).

    • Use a regular expression to determine when a certain browser (for instance, Microsoft Internet Explorer) is being used, and output a message to the user.

  3. The HTTP_REFERER (yes, it's spelt incorrectly in the protocol definition) environment variable contains the URL of the page from which the user followed a link to your CGI program. If you call up your CGI program by typing its URL straight into the browser, the HTTP_REFERER will be an empty string. Create an HTML page that points to your CGI program and see what the REFERER environment variable says.