CGI Tutorial

CGI Tutorial

CGI or Common Gateway Interface is a VERY powerful and useful computer language. It allows for a web designer to add a great amount of user interactivity to his/ her web site, along with many useful functions, like forms, quizzes, polls, page builders, free for all link pages and more. Unlike java script, cgi process data much more efficiently, writes to files much better and runs separate from HTML (except withSSI).

The first thing you need to know about CGI/perl is whether your host allows it or not and if they require .cgi extension or .pl extensions or both. If your host is Geocities, AOL, Tripod, AngelFire, or one of many more, cgi will not work so don't try to use it. If your host does allow cgi, have them set up a cgi-bin or something like one for your account. After you have done that, email them asking for the path to your root directory (may be like /usr/ait/htdocs/yourname/public_html/). Also ask them for the path to your send mail program (like /usr/bin/sendmail) and for the path to your date program (like /usr/bin/date/). You will also need to location of your perl interpreter (like #!/usr/bin/perl).

The very first part of every web ready script is defining the location of the perl interpreter, which is something like #!/usr/bin/perl/ or something like that. This is followed by the beginning of the script it's self. A good script will have all variables and comments after this.

$variable?

A varriable is a command that you will use to take data, write data and hold data with, it is a given value for something.

$variable = "line";

What this means is somewhere in the script it requires you to tell it what to do. For example if you were to have a program that prints your name it would ask you this...

$myname = "John";

And somewhere in the script is

print "My name is $myname\n";

The scripts see that it needs to print "My name is $myname\n"; and by defining $myname, it knows that $myname equals "John". The \n just tells the server to end the line.

Path and URL

CGI very often asks you to specify the path or URL to an HTML or another CGI page. It's very important that you don't get these two confused.

A path is directly relative to the current document. This is the path allocated by your server. A path will not work in the web browser, just the script. An example is:

/usr/www/docs/name/directory/

A URL, on the other hand, looks like this:

/15074/cgi-bin/vcenter.cgi

Other Important Codes

@array?

An array is used to keep and capture data, that will be used later in the script or from user information.

chop(item here)?

The chop function acts to remove the last character of a line form a data file or variable.

Printing information

Since the most common function in perl is printing information to the user, it becomes very important to know how to do it right,

The MIME (content) header is required whenever cgi prints out information. Without it, the browser would not know what it was displaying and would create a 500, server error).

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

Printing a standard line, with html code or without. Our first script also shows an example of printing

print "Hello, world!\n";




Your first script:
The first script we will show you is a simple script that prints one line of text. While it may seem simple, printint text is very important and necessary.

#!/usr/bin/perl
#first line ALWAYS goes to your perl interpreter
# hello.pl - a demo of a cgi that displays text
#

print "Content-type: text/html\n\n";
# the MIME content type
print "\n";
print "\n"; <br /> # The mandatory HTML head element<br /># and title element<br />print "Hello!\n"; <br /> print "\n";
print "\n";
print "Hello, world!\n";
# The print statement sends
# characters to the standard output
# with our actual message
print "\n";

The next script will be a little more complicated and list a few more variables, but does a lot more. This script tells about the environment it is hosted on by using $ENV.

#!/usr/bin/perl
# Purpose - shows us the environment
print "Content-type: text/plain\n\n";
print "Here is the environment:\n\n";
foreach $key (keys %ENV) {
printf "%16s = %s\n", $key, $ENV{$key};
# of the %ENV associative array
}

You will notice that this script does not require you to change anything other then the perl interpreter, which is very nice. However the next few scripts are not so easy.


This next script uses one variable and a simple array to write to a file and performs some interesting things. Enjoy.

#!/usr/bin/perl
#
# Purpose: to demonstrate the use of variables and arrays
$DATAFILE="data.dat";# you must make a file data.dat
#upload it and chmod 777
open(INP,"<$DATAFILE") || die "Can't open $DATAFILE.\n";
while(){
chop;
($name,$age) = split(/,/);
$person{$name} = $age;
}
close(INP);
print "Mike is " . &find_age("mike") . " year old.\n";
sub find_age{
($who) = @_;
$person{$who};
}

As you try this script, notice that there are variables to change and chmoding needed. Get use to chmoding (via telenet or ftp program) and to making variables, because they are very common in mostly all cgis. This script also shows how you can use a data file to find and store information.


This next script is one that most people like a lot, it is a random fortune (magic 8-ball script). It uses a pre made text file, a few variables and a lot of cgi to randomly pick what fortune to use. (note this script may be downloaded at our download center).

#!/usr/bin/perl
#
# Purpose : This script reads fortune file from FORTUNE.FUN and randomly picks
# a fortune cookie and displays it in HTML
#
print "Content-type: text/html\n\n";
# Change to the directory containing the TABLE.CSV file
# you can get the file at the downloads center
chdir "/temp";
# Global Settings
# this is the file with the fortunes (see download section)
$FUN_FILE="fortune.fun";
# Set the seed for the Perl randomizer
srand($$|time);
# Print the HTML header
print <

<br />Fortune Cookie CGI or other text here<br />


Your fortune cookie is:


HTMLHEADER
# Open the TABLE.CSV file
open(FUN,"<$FUN_FILE") || die "Error, Can't open $FUN_FILE\n";

# Initialize the count to zero
$count=0;

# Read the FORTUNE FUN file
while() {

# Remove the new line character from each line read.
chop;

# Store the line read in an scalar array called lines
$lines[$count]=$_;

# increase the count
# ++ ads 1 (c code)
$count++;

}

# Decrease once to adjust line count.
$count--;

# Close the file
close(FUN);

# Get a random number between 1 to $count
$random=int(rand($count)+1);

# Print the cookie
print <




$lines[$random]
COOKIE

# Print the HTML footer
print <

HTMLFOOTER

# End of FORTUNE.PL

As you probably noticed the script has a lot going on as compared to the other ones. But not to worry, just take it a line at a time, change the varibles and whatever other text you want changed. Run it and change some more. This script combines many functions, such as using a data file, arrays and loops. Also READ THE COMMENTS.


This next script is a counter cgi, which is very popular and not that hard to set up. The main difference with this script is that the web page is separate from the script and therefore you must make a page separate to use the script. Remember to change all the variables.

The Perl Code

#!/usr/bin/perl
#
# a simple counter script that counts the number of times a page has been accessed. #
# Tell Perl that we are going to use the CGI-LIB.PL library
# this file is downlaodable from our script center
require "cgi-lib.pl";
print &PrintHeader;
# Global variables
# the directory with the digits for the counter
$DIGIT_DIR = "digits";
# file to store data (chmod 777)
$COUNTER_FILE = "/logs/count.logs";
# Open the counter data file and read the count value in a variable
# Don't forget to close the file handle.
open(COUNT,$COUNTER_FILE) || die "Can't open $COUNTER_FILE\n";
$count=;
chop($count);
close(COUNT);
# Increment the read count.
$count++;
# Open the file for output and write the new count number and close the file
open(COUNT,">$COUNTER_FILE") || die "Can't open $COUNTER_FILE\n";
print COUNT $count,"\n";
close(COUNT);
# Split the count number by each digit and store them in an array called
# @digits
@digits = split(//,$count);
# Loop through each digit and create a tag and store it in a
# variable called $html
foreach $digit (@digits) {
$html .= < $digit
OUT
}

# Print out the html tag created in the previous loop.
print <




# Exit script.
exit 0;

The HTML code:




Sample Coutner CGI




This page has been accessed
WIDTH=60 HEIGHT=20 BORDER=0 />
times.








As you most likely noticed, this script requires another cgi called cgi-lib.pl, which is a cgi used by many scripts. It also requires for you to have images (digests) and a data file (chmod the filr 666). Besides that there is very little to edit. However, this script does contain many complicated loops and arrays. If you reference back to the first few scripts, it should be clear how these scripts work and what function they serve.

That is the last script we will explain, continue reading through the above scripts until you understand how to use arrays, variables, other scripts and html in cgi. Below is some information on how to use cgi script and other cgi related stuff. Enjoy.


Defining variables: This is the next part of a script and probably the part people make the most mistakes on, when defining variables you need to remember that a path may not always be http:// or anything like that. Since servers run off of internal, hidden directories, cgi is able to run though your host. Make sure all your variables point to the right location, and the right files. Also make sure these files are properly configured and chmoded correctly.

Chmoding is an important part of cgi scripting that can not be forgotten. What is does is tells the server how the script may be used and what may be done with it. Here are some common chmod commands.

Executability +755 (all the top row, bottom row and the left box in the middle row for ws_ftp).
Read Only +644 (just the top row in ws_ftp).
Read and some write +666 (top row and 2 left boxes in ws_ftp).
Write, Read, Execute by all +777 (every box in ws_ftp). No access +544 (no boxes checked in ws_ftp).

After you have chmoded the files, changed the variables and uploaded them, it is time to run the script. If you picked an essay script and did everything using the proper commands, ruining the script will work just fine. If you get a 500 error (internal server error), check the variables, chmod the file again and check the location of the perl interpreter. If it still does not work, check the script again, try starting over from an unedited copy, then ask the place where you got the script and/or your host.

Other things about CGI scripting: CGI scripting can be used for many things such as processing forms, and other cool little tricks, even counters. There are a great number of free scripts out there, we have made a few and added some free ones to our script center. Check them out, try them out and enjoy them. If you need more specific help, send us an email us.


No comments:

 

$html