The Common Gateway Interface

This document is intended to ease you into the idea of writing your own CGI programs with simplified examples and explanation which is less technically oriented than the interface specification itself.


How do I get information from the server?

Each time a client requests the URL corresponding to your gateway, the server will execute your program. The output of your program will go more or less directly to the client.

A common misconception about CGI is that you can send command-line switches to your program, such as foobar -qa blorf. CGI uses the command line for other purposes and thus this is not directly possible. Instead, CGI uses environment variables to send your program its parameters. The two major environment variables you will use for this purpose are:


How do I send my document back to the client?

I have found that the most common error in beginners' CGI programs is not properly formatting the output so the server can understand it.

CGI programs can return a myriad of document types. They can send back an image to the client, and HTML document, a plaintext document, or perhaps even an audio clip of your bodily functions. They can also return references to other documents. The client must know what kind of document you're sending it so it can present it accordingly. In order for the client to know this, your CGI program must tell the server what type of document it is returning.

In order to tell the server what kind of document you are sending back, whether it be an document or a reference to one, CGI requires you to place a short header on your output. This header is ASCII text, consisting of lines separated by either linefeeds or carraige returns followed by linefeeds. Your program must output at least two such lines before its data will be sent directly back to the client.

The first line will be different depending on whether your program is returning a full document or a reference to one:

Next, you have to send the second line. With the current specification, THE SECOND LINE SHOULD BE BLANK. This means that it should have nothing on it except a linefeed. Once the server retrieves this line, it knows that you're finished telling the server about your output and will now begin the actual output. If you skip this line, the server will attempt to parse your output trying to find further information about your request and you will become very unhappy.

Advanced usage: If you would like to output headers such as Expires or Content-encoding, you can if your server is compatible with CGI/1.1. Just output them along with Location or Content-type and they will be sent back to the client.


Return to the overview

Rob McCool [email protected]