The Common Gateway Interface (CGI) is a standard (see RFC 3875: CGI Version 1.1) that defines how web server software can delegate the generation of web pages to a text-based application. Such applications are known as CGI scripts; they can be written in any programming language, although scripting languages are often used.
The task of a web server is to respond to requests for web pages issued by clients (usually web browsers) by analyzing the content of the request (including the URL, the HTTP 'method', request headers and any message body), determining appropriate actions to take and creating an appropriate document to send in response, then returning that to the client. CGI also defines how the application should pass back extra information about the output (such as the MIME type and other response headers).
If the requested file exists on disk, the server can just return the file's contents. Alternatively, the document's content may need to be composed on the fly, and other actions such as updating a database, may be required. One way of achieving this is for a console application to handle the request and compute the returned document's contents. The web server executes the console application and returns its output to the client (typically a web browser). CGI specifies which information is communicated between the web server and such a console application, and how.
The web server software will invoke the console application as a command. CGI defines how information about the request (such as the URL, request headers etc) is passed to the command in the form of arguments and environment variables. The application then writes the output document to standard output.
From the Web server's point of view, certain locators, e.g. http://www.example.com/wiki.cgi, are defined as corresponding to a program to execute via CGI. When a request for the URL is received, the corresponding program is executed.
Web servers often have a cgi-bin/ directory at the base of their directory tree to hold executable files called with CGI.
Full article ▸