Introduction to the Common Gateway Interface (CGI)
How does CGI work?
Web servers receive requests from clients and send back responses. Usually when a web
server receives a request, it just locates the requested file, and sends this file back as
the response. However when the requested file is a CGI application, the web server
executes the application, and sends the output of the application back as the response.
Both the web server, and the application must cooperate for this process to work. The
duties of both are described below.
Web Servers & CGI
The web server's duties are as follows: First the web server must determine that the
file being requested is actually a CGI application, then the web server must executes the
CGI application, passing it certain information. This information is passed to the
application in environment variables, and sometimes through the standard input stream.
Next the web server captures the output of the application. Finally the web server sends
back the response (this may involve adding response headers). Response headers are a few
lines at the front of a response, that describe the response so that the client knows what
to expect. Usually the CGI application doesn't need to output the full response header,
but leaves that up to the web server.
CGI Applications
The duties of the CGI application are as follows: Gather any information that was
passed to it, by reading the environment variables and/or reading from the Standard Input,
then do whatever it was written to do, making sure to write an output response to the
Standard Output Stream.
That's It!
The two previous paragraphs pretty much describe the CGI specification. Left out were
details like:
- which environment variables are used to pass information to the CGI application
- what information is contained in the environment variables
- what information is passed through Standard Input
- how this information is encoded
- how does the web server know whether or not to add response headers.
Also useful to know but not part of the CGI specification are
- what are the possible response headers
- HTML (so that the CGI application can generate valid responses, and so that you know how
to make your web pages refer to the CGI application).
A question that might have occurred to you is "how does the web server know when a
request is made for a file, whether the file is a CGI application or not?". The CGI
specification does not describe how this is done, but leaves that up to the web server. A
common solution is to configure the web server to assume that any file ending with .cgi
is a CGI application. Another common solution is to treat any file in a particular
directory as a CGI application.
Next > Web Server installation |