Running CGI Scripts in UISacad

.htaccess files
A .htaccess file is a way to set configuration directives on a per-directory basis. When Apache serves a resource, it looks in the directory from which it is serving a file for a file called .htaccess, and, if it finds it, it will apply directives found therein.

Enabling CGI access in your account
Choose a directory where you want cgi enabled on. This directory must be somewhere inside your public_html directory. The easiest thing to do is to create a directory called cgi-bin inside your public_html directory. Using your favorite editor create a file called .htaccess in that directory. In the .htaccess file, you’ll need the following directives:

Options +ExecCGI
AddHandler cgi-script cgi pl

This tells Apache that execution of CGI programs is permitted in this directory and that your cgi scripts will have the extension .cgi or .pl.

Writing a CGI program
There are two main differences between “regular” programming, and CGI programming.

First, all output from your CGI program must be preceded by a MIME-type header. This is HTTP header that tells the client what sort of content it is receiving. Most of the time, this will look like:

Content-type: text/html

Secondly, your output needs to be in HTML, or some other format that a browser will be able to display. Most of the time, this will be HTML, but occasionally you might write a CGI program that outputs a gif image, or other non-HTML content.

Apart from those two things, writing a CGI program will look a lot like any other program that you might write.

Your first CGI program
The following is an example CGI program that prints one line to your browser. Type in the following, save it to a file called, and put it in the cgi directory you just created.

print “Content-type: text/htmlrnrn”;
print “Hello, World.”;

Even if you are not familiar with Perl, you should be able to see what is happening here. The first line tells Apache (or whatever shell you happen to be running under) that this program can be executed by feeding the file to the interpreter found at the location /usr/bin/perl. The second line prints the content-type declaration we talked about, followed by two carriage-return newline pairs. This puts a blank line after the header, to indicate the end of the HTTP headers, and the beginning of the body. The third line prints the string “Hello, World.” And that’s the end of it.

If you created your cgi-bin directory inside your public_html directory then open your favorite browser and tell it to get the address:

or wherever you put your file, you will see the one line Hello, World. appear in your browser window. It’s not very exciting, but once you get that working, you’ll have a good chance of getting just about anything working.

Information on this page was obtained from Apache’s website.