[ Table of Contents ] [ Previous Chapter ] [ Next Chapter ]



Using CGIs

In general, when traversing a Web page, clicking on a link causes that client (browser) to send a message to the server (the site maintaining the Web page the client wishes to view) with a given URL. The server gets the file indicated by the URL and sends the contents of the file back to the browser to be displayed to the user. The Common Gateway Interface (CGI) is a mechanism that causes the server to behave differently.

 

The CGI protocol defines communication between the server and an external program. When the URL points to a CGI script file, instead of simply sending the contents of the file to the browser, the server executes the script and then returns the program output to the browser. This allows Webmasters to create dynamic documents and interactive pages.

 

Shell CGIs

A shell CGI is a text file that contains commands for the Bourne Shell or C Shell command interpreter. Any text editor can be used to create shell CGIs. The resultant file will typically have the file extension of " .sh " (e.g., mycgi.sh ). Place the file in the iTools cgi-bin folder.

 

The simplest CGI to create and use -- the shell CGI -- is a text file that contains commands for the Bourne Shell command interpreter. The steps are as follows:

 

Create a CGI called mycgi.sh. Store the newly created file in the cgi-bin directory. The new CGI can be referenced from a browser with the following URL: /cgi-bin/<cgi-name>. If mycgi.sh is stored in the cgi-bin directory, the URL would be: /cgi-bin/mycgi.sh.

 

Basic Steps

 

Required Shell Script Content

In addition to creating the text file, there are a few important considerations with respect to the content of the file. First, the top line of the file must contain the following text:

 

#!/bin/sh

 

This tells the system that this is a Bourne Shell script and that the Bourne Shell should be used to interpret the rest of the script.

 

Second, you can use the echo command to generate text which will be returned to the browser that initiated the URL. The first echo command must contain the following Bourne Shell commands to generate HTTP. This puts iTools and the browser in the proper mode to accept everything else:

 

echo Content-type: text/plain

echo

 

The first echo indicates that text/plain will follow. The second echo is necessary in order to get the HTTP interpreter to accept the Content-type request. After that, any text sent with an echo command is printed on the originating browser's screen as a response to the URL request.

 

Shell scripts are text files containing Bourne Shell commands that can generate a stream of characters in response to being executed. There are Bourne Shell commands for assigning integer and string values to shell variables, commands for prescribing conditional flow through the shell script, and commands for running other programs. Relatively sophisticated CGIs can be created by combining different Bourne Shell commands. There are a number of widely available books describing Bourne Shell programming.

 

Bourne Shell CGIs are used for low-performance, easy-to-develop CGIs. Each Bourne Shell script is text, and is interpreted by a Bourne Shell interpreter controlled by iTools. Since the interpreter interprets each command, shell scripts operate fairly slowly and use a large number of processing cycles. Therefore, Bourne Shell scripts should be used primarily for rapid CGI development or CGI prototyping. If a CGI will be used in high volume, you may want to consider constructing a more efficient C Language CGI or a Perl CGI.

Printenv.sh Example

 

A sample shell CGI is included in the printenv.sh file located in the iTools cgi-bin directory. The first few lines of the file establish the mandatory #!/bin/sh and echo Content-type: text/plain requirements for any shell script. The remaining shell script commands are used to output a few lines of constant text, followed by a dozen or more lines that output the values of a family of shell variables. The following is the content of the printenv.sh CGI:

 

#!/bin/sh

# disable filename globbing

set -f

echo Content-type: text/plain

echo

echo CGI/1.0 test script report:

echo

echo argc is $#. argv is "$*".

echo

echo SERVER_SOFTWARE = $SERVER_SOFTWARE

echo SERVER_NAME = $SERVER_NAME

echo GATEWAY_INTERFACE = $GATEWAY_INTERFACE

echo SERVER_PROTOCOL = $SERVER_PROTOCOL

echo SERVER_PORT = $SERVER_PORT

echo REQUEST_METHOD = $REQUEST_METHOD

echo HTTP_ACCEPT = "$HTTP_ACCEPT"

echo PATH_INFO = "$PATH_INFO"

echo PATH_TRANSLATED = "$PATH_TRANSLATED"

 

echo QUERY_STRING = $QUERY_STRING

 

echo SCRIPT_NAME = $SCRIPT_NAME

echo REMOTE_HOST = $REMOTE_HOST

echo REMOTE_ADDR = $REMOTE_ADDR

echo REMOTE_USER = $REMOTE_USER

echo AUTH_TYPE = $AUTH_TYPE

echo CONTENT_TYPE = $CONTENT_TYPE

echo CONTENT_LENGTH = $CONTENT_LENGTH

 

When the printenv.sh CGI is referenced by a URL, it produces the following output:

 

CGI/1.0 test script report:

argc is 0. argv is .

SERVER_SOFTWARE = Apache/1.2b10 iTools/1.0b8.7

SERVER_NAME = ppc0.tenon.com

GATEWAY_INTERFACE = CGI/1.1

SERVER_PROTOCOL = HTTP/1.0

SERVER_PORT = 81

REQUEST_METHOD = GET

HTTP_ACCEPT = image/gif, image/x-xbitmap, image/jpeg, image/pjpeg,

PATH_INFO =

PATH_TRANSLATED =

SCRIPT_NAME = /cgi-bin/printenv.sh

QUERY_STRING =

REMOTE_HOST = 205.180.86.8

REMOTE_ADDR = 205.180.86.8

REMOTE_USER =

AUTH_TYPE =

CONTENT_TYPE =

CONTENT_LENGTH =

 

 

Shell Variables

 

Shell variables are pre-defined values set by iTools before the shell CGI is started. Shell variables are referenced by placing a "$" character in front of the

name of the shell variable. If the shell interpreter finds a name that matches the string of characters following any "$" character, it substitutes the value of that

variable in its processing. In the case of the echo command, the value of the $VAR shell variable is substituted as a parameter to the echo command and is

output to the browser as a partial response to the URL request.

 

Perl CGIs

A Perl CGI is a text file that contains commands for the Perl language interpreter. The file name extension is usually " .pl ", and the file is placed in the cgi-bin folder. A Perl interpreter is included with iTools, so iTools is able to interpret Perl scripts.

 

This document describes iTools Perl CGIs. A Perl CGI is a text file that contains commands for the Perl language interpreter.

 

Create a new CGI called mycgi.pl.

 

Store the newly created file in the cgi-bin directory, under the iTools cgi-bin directory. The new CGI can be referenced from a browser with the following URL: /cgi-bin/<cgi-name>.

Required Script Content

 

In addition to creating the text file, there are a few important considerations with respect to the content of the file. First, the top line of the file must contain the text:

 

#!/usr/bin/perl

 

This tells the iTools system that this is a Perl script and that Perl should be used to process the remainder of the file.

 

Second, you can use Perl print statements to generate text which will be returned to the browser that initiated the URL. The first print command must contain an HTTP header. This header indicates what format or kind of data will be output by the remainder of the print commands. The choices are usually plain text or text that is marked up using the HyperText Markup Language (HTML). This first print command puts iTools and the browser in the proper mode to accept everything else.

 

For Perl scripts that output plain text, use:

 

print "Content-type: text/plain \n\n";

 

For Perl scripts that output HTML statements, use:

 

print "Content-type: text/html \n\n";

 

The print indicates that text/plain or text/html will follow. After that, any text generated with a print command is sent to the originating browser as a response to the URL request.

 

Perl scripts are text files containing Perl language statements that generate a stream of text characters in response to being executed. There are Perl statements for assigning integer and string values to variables, statements for prescribing conditional flow through the script, and statements for running other programs. Very sophisticated CGIs can be created by combining different Perl statements. A number of widely available books describing Perl programming are available.

 

Programming Perl, Second Edition by Larry Wall, Tom Christiansen and Randal L. Schwartz, with Stephen Potter. 1996, O'Reilly & Associates

 

Perl is used for medium-performance, easy-to-develop CGIs. Each Perl program is text. The scripts are interpreted by a Perl interpreter controlled by iTools. Since the interpreter interprets each Perl statement, Perl scripts can consume a lot of memory and use a large number of processing cycles.

 

Printenv.pl Example

 

A sample Perl CGI is included in the .printenv.pl file located in the iTools cgi-bin directory. The first few lines of the file establish the mandatory #!/usr/bin/perl and print Content-type: text/plain requirements for any Perl script. The remaining two Perl statements output a dozen or more lines that contain the values of a family of environment variables. The following is the content of the printenv.pl CGI:

 

#!/usr/bin/perl

 

print "Content-type: text/html\n\n";

while( ($key,$val) = each %ENV ) { print "$key = $val<BR>\n"; }

 

When the printenv.pl CGI is referenced by a URL, it produces the following output:

 

SERVER_SOFTWARE = Apache/1.3.9 iTools/5.0

GATEWAY_INTERFACE = CGI/1.1

DOCUMENT_ROOT = /Local/Library/WebServer/WebSites

REMOTE_ADDR = 205.180.86.12

SERVER_PROTOCOL = HTTP/1.0

REQUEST_METHOD = GET

REMOTE_HOST = 205.180.86.12

HTTP_REFERER = http://fred.tenon.com/examples/default.html

QUERY_STRING=

HTTP_USER_AGENT=Mozilla/3.0 (Macintosh; I; PPC)

PATH = /bin:/usr/bin:/usr/ucb:/usr/bsd:/usr/local/bin

HTTP_ACCEPT = image/gif, image/x-xbitmap, image/jpeg, image/pjpeg,

REMOTE_PORT = 1046

HTTP_PATH_CONTROL = Max-age=259200

SCRIPT_NAME = /cgi-bin/printenv.pl

SCRIPT_FILENAME = /Local/Library/WebServer/cgi-bin/printenv.pl

SERVER_NAME = fred.tenon.com

REQUEST_URI = /cgi-bin/printenv.pl

HTTP_X_FORWARDED_FOR = 205.180.86.12

SERVER_PORT = 81

HTTP_HOST = fred.tenon.com

HTTP_VIA = 1.0 fred.tenon.com:80 (Squid/1.1.9.3)

SERVER_ADMIN = webmaster

 

Environment Variables

 

Environment variables are pre-defined values set by iTools before the Perl CGI is started. Environment variables are referenced by the Perl statement $ENV{<env var>}. The Perl statement:

 

$ENV{PATH} = "/bin:/usr/bin";

 

sets the PATH environment variable. The Perl statement:

 

print $ENV{PATH};

 

prints the current value of the PATH environment variable.

 

 

C Language CGIs

A C language CGI is a computer program. To produce a C language CGI, you need to write the C language source program using any text editor. Then, a C language translator called a C compiler is needed to translate the C program into machine language. The machine language file with the extension " .c " is stored in the cgi-bin folder in a file that can be executed by iTools.

 

A C Language CGI is a computer program. To produce a C Language CGI you must first write the C Language source code using a text editor program. Once the program is written, a C Language translator, called a C compiler, is used to translate the C Language into machine language.

 

Create a new CGI called mycgi.c. Once the C Language source file is constructed, invoke the C Language compiler using the following format:

 

cc -O -o mycgi mycgi.c

 

This command produces a machine language file named mycgi using the C Language source found in the file mycgi.c. The resulting machine language file or objectfile is directly executable under iTools. You can use debugging techniques to ensure that the C Language CGI operates correctly. Once the CGI is complete, store the CGI in the iTools cgi-bin directory. Then reference the CGI with the following URL: /cgi-bin/mycgi

 

The CGI will be invoked by iTools and the output will be transported to your browser.

 

Basic Steps

C Language CGIs are used for high-performance CGIs. Since each C Language CGI is a compiled program, executing a C Language CGI reaps the full benefit of the fastest performance than can be delivered.

Printenv.c Example

The C Language CGI example included with iTools is in a file named printenv.c, which is located in the iTools cgi-bin directory.The printenv source code is in tenon/examples/printenv.c.text. Below is the content of the printenv.c CGI:

 

#include <stdio.h>

#include <stdlib.h>

typedef struct {

char name[128];

char val[128];

} entry;

void getword(char *word, char *line, char stop);

char x2c(char *what);

void unescape_url(char *url);

void plustospace(char *str);

 

entry entries[10000];

 

main(int argc, char *argv[]) {

register int x,m=0;

char *cl;

 

printf("Content-type: text/html%c%c",10,10);

 

if(strcmp(getenv("REQUEST_METHOD"),"GET")) {

printf("This script should be referenced with a METHOD of GET.\n");

printf("If you don't understand this, see this ");

printf("<A HREF=\"http://www.ncsa.uiuc.edu/SDG/Software/Mosaic/Docs/fill-out-forms/overviewhtml\">forms

overview</A>.%c",10);

exit(1);

}

 

cl = getenv("QUERY_STRING");

if(cl == NULL) {

printf("No query information to decode.\n");

exit(1);

}

for(x=0;cl[0] != '\0';x++) {

m=x;

getword(entries[x].val,cl,'&');

plustospace(entries[x].val);

unescape_url(entries[x].val);

getword(entries[x].name,entries[x].val,'=');

}

 

printf("<H1>Query Results</H1>");

printf("You submitted the following name/value pairs:<p>%c",10);

printf("<ul>%c",10);

 

for(x=0; x <= m; x++)

printf("<li> <code>%s = %s</code>%c", entries[x].name, entries[x].val,10);

printf("</ul>%c",10);

}

 

This CGI prints the name/value parameter pairs that are available to any CGI when the CGI is invoked. The general flow of the printenv CGI is that it uses the printf statement to output Content-type: text/html\n\n. This is needed in order for the CGI to inform iTools and the remote browser of the type of content to follow.

 

The program then verifies whether or not a GET type of HTTP request was used to initiate the CGI. If a GET request was not used, an error message is returned with several printf statements and the program exits. If a GET HTTP request is found, the environment variable QUERY_STRING is requested. If that string is unavailable, an error message is printed and the program exits. If QUERY_STRING is found, a for loop is entered. The for loop calls the getword subroutine to parse the string into name and value pairs. Once all of the parameters have been parsed, the printf subroutine is called several times to output a constant string "QUERY RESULTS", followed by the string "You submitted the following name/value pairs:", followed by a name and value pair on each line until all of the name/value parameters have been displayed. When the printenv CGI is referenced by the URL:

 

/cgi-bin/printenv?company=Tenon Intersystems&addr=1123 Chapala St.&city=Santa Barbara

 

it produces the following output:

 

Query Results

 

You submitted the following name/value pairs:

 

company = Tenon Intersystems

addr = 1123 Chapala St.

city = Santa Barbara

 

 

Fast CGI

iTools includes built-in support for the execution of FastCGI scripts. FastCGI scripts are faster than normal CGI scripts because they are always running while normal CGIs are re-loaded each time they are explicitly run. Any CGI can take advantage of FastCGI capabilities if the script's code is modified. Below is an example of the simple printenv.pl script in the form of a FastCGI. The "use CGI::Fast;" line makes the FastCGI capabilities available to the script. The "while" loop must contain the CGI's code. The "$query" variable will change every time the CGI is used by a cliend and therefore can be used to track eawhich request is being processed

.

#!/usr/bin/perl

use CGI::Fast;

while ($query = new CGI::Fast)

{

print "Content-type: text/html<BR>\n";

while (($key, $val) = each %ENV) {

print "$key = $val<BR>\n";

}

}

 

When a FastCGI such as this is run the first time, mod_fastcgi (an Apache module) spawns a process that keeps the script running while Apache is running. To have the FastCGI run automatically when Apache is first started, put the following lines in the apache.conf file:

 

<IfModule mod_fastcgi.c>

FastCGIServer /Local/Library/WebServer/CGI-Executables/printenv.fcgi -processes 1

</IfModule>

 

These lines will create one instance of the printenv.fcgi script whenever Apache is run. The number of processes can be increased if more instances are needed to accommodate the volume of requests. All FastCGI scripts are named with the ".fcgi" extension by convention. Be sure to set the correct path to the FastCGI script in the Apache directives given.

 



[ Table of Contents ] [ Previous Chapter ] [ Next Chapter ]



Copyright 1999. Tenon Intersystems. All Rights Reserved.