Use the SERVER_NAME environment variable
The script has
access to the domain name of the virtual server via
$ENV{'SERVER_NAME'}.
Use this environment variable instead of hard-wiring
the server name throughout the code:
$myserver = $ENV{'HTTP_HOST'} ||
$ENV{'SERVER_NAME'};
By using SERVER_NAME, your CGI script will not be
sensitive if you change the domain name at a later date.
Use the DOCUMENT_ROOT environment variable
Avoid using
absolute paths to your data files (i.e. /usr/home/yourname.com/file.txt). Use
$ENV{'DOCUMENT_ROOT'} instead. This variable is of the form:
/usr/home/yourname.com/htdocs
By using DOCUMENT_ROOT, your CGI script
will not be sensitive to changes in directory structure, or changes in domain
name. The following table shows the most common paths in terms of
DOCUMENT_ROOT:
Home directory |
Absolute
path: |
Document root |
Absolute
path: |
CGI-BIN directory |
Absolute
path: |
Use the SCRIPT_NAME environment variable
A common mistake
is to hard-wire the script name throughout the code, or via a configuration
parameter. However, this is unnecessary. The script has access to its name as
$ENV{'SCRIPT_NAME'}:
$myserver = $ENV{'HTTP_HOST'} ||
$ENV{'SERVER_NAME'};
$myurl =
"http://$myserver$ENV{'SCRIPT_NAME'}";
By using SCRIPT_NAME, your CGI
script will not be sensitive if you choose to rename it at a later
date.
Use the HTTPS environment variable
Don't hard-wire
the "http://" into the script, especially if you plan to use secure server. Use
$ENV{'HTTPS'} instead:
$myserver = $ENV{'HTTP_HOST'} ||
$ENV{'SERVER_NAME'};
$myhttp = $ENV{'HTTPS'} ? "https://" :
"http://";
$myurl = "$myhttp$myserver$ENV{'SCRIPT_NAME'}";
By using
HTTPS, your CGI script will not be sensitive if you choose to move it to/from a
secure server environment.
Use other environment variables
Many other
environment variables are available for your use. By using environment variables
instead of hard-wiring variables, you will be able to seamlessly move scripts
between servers, between drives, to/from a secure server environment, and even
rename the script, all without the need to edit the script.
For a list of
environment variables available to your CGI script, please visit /cgi-bin/env.pl
which is pre-installed into your /cgi-bin directory.