4.2.1.2.1.1.1. Sample Perl code

You don't need a lot of code in your web application to implement the redirection. The following Perl code is a section of a sample browser handler.

#!/usr/bin/perl
eval { &main; };
if ($@){ &cgierr("$@"); }
exit;

sub main{
# Your Perl code to detect the browser and the appropriate content format
# goes here.
# The variable $format contains the sub-directory's name to the web page
# requested in the appropriate format, like "xhtmlbasic".
# $ENV{'QUERY_STRING'} should be checked before for unsuitable characters often 
# used by hackers. Otherwise, the printing of unknown strings may cause crashes.
 print "Location: http://myserversdomainname/$format$ENV{'QUERY_STRING'}\n\n";
}

sub cgierr {
 print qq|Content-type: text/html

<html><body><pre>CGI ERROR\n|;
 @_ and print "Error Message: @_\n";
 print "</pre></body></html>";
 exit -1;
}

The section does not contain the necessary code for the browser detection and selection. It describes which code is used to send the server response. The main piece of code is the line print "Location: http://myserversdomainname/$format$ENV{'QUERY_STRING'}\n\n";. The browser handler does not need to send the whole HTTP header and body. It only needs to print the "Location" HTTP header field containing the new URL.

You must replace the string "myserversdomainname" by the actual domain name of your server.

The Perl hash %ENV comprises all CGI environment variables. One of these environment variables is the "QUERY_STRING". The value of this environment variable is referenced by $ENV{'QUERY_STRING'}. If the initial URL is "http://www.foobar.com/?/news/20010207.html", then the value of $ENV{'QUERY_STRING'} is "/news/20010207.html". If we assume, that the variable $format has the value "xhtmlbasic", the Perl script would print out the string "Location: http://www.foobar.com/xhtmlbasic/news/20010207.html".

Copyright © 2001-2003 by Rainer Hillebrand and Thomas Wierlemann