Browse Sections

CGI Programming (Part 2)


Who is this for
This article provides a sample CGI script to show what you can do with CGI programming.

What you Need to Have by Now
Skills: Perl programming, Basic HTML
Environment: Webserver setup to run you CGI scripts.

What Can You Do With CGI Scripts
When you have a static HTML page, you can display whatever information you want. However, if you want to get a little fancier, like allow users to enter data on your page and process the data, or simply to include the current date and time in your HTML page, you will need to write some scripts. This is where CGI comes in. Simply put, a CGI script is a program that generates an HTML page. How you generate your HTML page depends your requirements. Your CGI script can be written in any language but most CGI scripts are written in Perl.

The %ENV hash
When your server starts your CGI script, it contains several general information that your script can use. Among the more useful information in the %ENV hash are:
KEY Description
QUERY_LENGTH Length of the input data
QUERY_STRING Input data to be passed to the script
SERVER_ADDR IP address of your server
HTTP_HOST Name of your server
SCRIPT_NAME Name of your script. This is the string after the http://hostname
DOCUMENT_ROOT The starting path for all your documents
REQUEST_METHOD Specifies how your CGI is to process the data that is being passed from the HTML page
HTTP_COOKIE Cookie set for this CGI

To see all the keys in the %ENV hash, create this program and save it in your cgi-bin directory. Remember, your cgi-bin directory should be defined to run CGI scripts. Otherwise, you will get weird results.

#!/usr/bin/perl
print "Content-type: text/html\n\n";
foreach (sort keys %ENV) {
          print "<B>$_</B&gt: $ENV{$_}&ltBR>\n";
}


To see the result, save this as parm.cgi in your cgi-bin directory. Then on your browser, typehttp://localhost/cgi-bin/parm.cgi This is assuming that your cgi-bin directory is called cgi-bin. I have saved this on a free CGI server and unfortunately, the server is not reliable. You may want to check it anyway by clicking on this link. Now that you see that you can get data from an HTML page, you probably have an idea of what you can do with CGI scripts.A Sample Form
Let us say that you want to create a sample Guestbook. The Guestbook can
The copyright of the article CGI Programming (Part 2) in Perl is owned by Philip Yuson. Permission to republish CGI Programming (Part 2) in print or online must be granted by the author in writing.

Go To Page: 1 2

Articles in this Topic    Discussions in this Topic