CGI and Perl

Included Files

One feature that is provided by some Web servers is server-side includes. You can configure your Web server in such a way that files of certain extensions (let's use the common one, .shtml) are parsed by the server before they are sent down to the client. There are two directives that tell the server to perform a specific operation with the file.




The server-side include feature is used to dynamically include nested HTML files. This feature enables some limited dynamically created content. The include directive is used to include other HTML files, much like a C program including header files. The echo directive allows you to dynamically display certain variables. The variables that can be displayed using the echo directive are as follows:


As you saw previously, all of the HTML that you generate from your Perl script is dynamic. It would be very easy to incorporate this kind of information using simple print statements. For example, to print the local date, instead of using an echo directive you might write the following:

print "The current local time is: " . localtime() . "\n";

Or, to print Greenwich Mean Time, you could write:

print "The current time in Greenwich is: " . gmtime() . "\n";

The include directive of server-side includes can be easily implemented in Perl code, as in List-ing 4.2.

Listing 4.2. Perl subroutine for including another HTML file.

 sub includeHTMLFile {
     open(IN,"< $thePathToHTMLFile") ||
         die "Cannot open file: $thePathToHTMLFile for read!\n";

In this example, the CGI environment variable DOCUMENT_ROOT determines the location of the included file. This is one of several well-defined environment variables for use in CGI programming.

You can extend the function in Listing 4.2 to process .shtml files and perform the proper action on the directives. Listing 4.3 shows a CGI program that uses the PATH_INFO environment variable to specify the .shtml file to parse. This CGI program can be specified as PATH_INFO will contain /included.shtml, and that document will be returned with the proper SSI parsing having taken place.