Gsharp Training Material Home Table of Contents

Common Gateway Interface


The server is normally set up so that when a page is requested from the cgi-bin directory then rather then sending the contents of the requested file, it runs the file and sends back the output instead.

It is also possible to specify that the server should run any files that ends in .cgi.

In other words, files in the cgi-bin directory must be executable and create an HTML file on stdout. The script does not care about the contents of the file - it just executes it and uses the output. The script can use the name/value pairs that it receives to determine the HTML that it creates.

Common languages for writing CGI scripts in are shell scripts, perl scripts and the Gsharp Script Language (GSL).

The first job a script must do is declare the format of the file that it is creating. This is normally text/html but could also be something like image/gif.

#!/usr/sbin/perl

print "Content-type: text/html\n\n";
print "<HTML>\n";
...
#!/bin/sh

echo "Content-type: text/html"; echo
echo "<HTML>"
...
#!/bin/GsharpWE

include "$UNIDIR/lib/libhtml.gsl";

HTTPheader();

HTMLheader(stdout,"This is the title","Advanced Visual Systems");
HTMLheading(stdout, 1, "This is my heading");
HTMLfooter(stdout);
#!/bin/sh

echo "Content-type: image/gif"; echo
cat /usr/GsharpWE/example/GsharpWE/gscube10.gif

How the script has access to the name/value pairs is dependent on the method specified in the form. If method=get (the default) then the pairs are attached to the end of the requested page.

/cgi-bin/process.cgi?name1=value1&name2=value2

Text fields: Pull-down menus:

The server places the pairs into the environment variable QUERY_STRING


If method=post then the script must read the pairs from stdin. This method is recommended for large numbers of pairs as some systems have a limit to the size of the environment.

Text fields: Pull-down menus:

The number of characters waiting in stdin can be found in the environment variable CONTENT_LENGTH.


In order to use the name/value pairs the QUERY_STRING must be parsed. There are a number of programs to do this. If you are using perl you could use the following code:

# Process cgi args

if( $ENV{'REQUEST_METHOD'} eq "GET" )
{
   $buffer=$ENV{'QUERY_STRING'} ;
}
else
{
   read(STDIN, $buffer, $ENV{'CONTENT_LENGTH'}) ;
}
@pairs = split(/&/, $buffer) ;
foreach (@pairs)
{
   tr/+/ / ;
   ($name,$value)=  split(/=/) ;
   $value        =~ s/%(..)/pack("c",hex($1))/ge ;
   $name         =~ s/%(..)/pack("c",hex($1))/ge ;

   $in{$name} = $value;

}

If you are using the Gsharp Web Edition then the input is automatically parsed. The value of each name is stored in a string dataset FORM_name. For example, if you request /cgi-bin/process.gsl?title=hello&height=3 then process.gsl will be run with two datasets already created:

FORM_title="hello"; FORM_height="3";