The Common Gateway Interface

After reading this document, you should have an overall idea of what a CGI program needs to do to function.

How do I get information from the server?

Each time a client requests the URL corresponding to your CGI program, the server will execute it in real-time. 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 options and arguments to your program, such as

     command% myprog -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, an HTML document, a plaintext document, or perhaps even an audio clip. 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 a full 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 carriage returns (or both) followed by a single blank line. The output body then follows in whatever native format.

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.