Common Gateway Interface

This article is about the software interface between a web server and programs. For other uses, see CGI (disambiguation).

In computing, Common Gateway Interface (CGI) offers a standard protocol for web servers to interface with executable programs running on a server that generate web pages dynamically. Such programs are known as CGI scripts or simply as CGIs; though usually written in a scripting language, they can be written in any programming language.


The official CGI logo from the spec announcement

In 1993 the National Center for Supercomputing Applications (NCSA) team wrote the specification for calling command line executables on the www-talk mailing list;[1] however, NCSA no longer hosts the specification.[2][3] The other Web server developers adopted it, and it has been a standard for Web servers ever since. A work group chaired by Ken Coar started in November 1997 to get the NCSA definition of CGI more formally defined.[4] This work resulted in RFC 3875, which specified CGI Version 1.1. Specifically mentioned in the RFC are the following contributors:[5]

Purpose of the CGI standard

Each Web server runs HTTP server software, which responds to requests from Web browsers. Generally, the HTTP server has a directory (folder), which is designated as a document collection — files that can be sent to Web browsers connected to this server.[6] For example, if the Web server has the domain name, and its document collection is stored at /usr/local/apache/htdocs in the local file system, then the Web server will respond to a request for by sending to the browser the (pre-written) file /usr/local/apache/htdocs/index.html.

But what if a web server must return a page that is constructed on the fly, in response to the request? In such cases, software must be used to construct the page. That software doesn't need to be part of the webserver software itself. It can be a separate program, called by the webserver software when a request comes in, and responding by returning the constructed document to the webserver software, which in turn sends it back to the requesting client (usually, a web browser that displays it to the end user). In the early days, such programs were usually small and written in a scripting language; hence, they were known as scripts.

Such programs usually require some additional information to be specified with the request. For instance, if Wikipedia were implemented as a script, one thing the script would need to know is whether the user is logged in and, if logged in, under which name. The content at the top of a Wikipedia page depends on this information.

HTTP provides ways for browsers to pass such information to the webserver, e.g. as part of the URL. The webserver software must then pass this information through to the script somehow.

Conversely, upon returning, the script must provide all the information required by HTTP for a response to the request: the HTTP status of the request, the document content (if available), the document type (e.g. HTML, PDF, or plain text), etcetera.

Initially, different webserver software would use different ways to exchange this information with scripts. As a result, it wasn't possible to write scripts that would work unmodified for different webserver software, even though the information being exchanged was the same. Therefore, it was decided to establish a standard way for exchanging this information: CGI (the Common Gateway Interface, as it defines a common way for webserver software to interface with scripts). Webpage generating programs invoked by webserver software that operate according to the CGI standard are known as CGI scripts.

This standard was quickly adopted and is still supported by all well-known webserver software, such as Apache, IIS, Nginx, and (with an extension) node.js-based servers.

Using CGI scripts

A webserver allows its owner to configure which URLs shall be handled by which CGI scripts.

This is usually done by marking a directory within the document collection as containing CGI scripts - its name is often cgi-bin.. For example, /usr/local/apache/htdocs/cgi-bin could be designated as a CGI directory on the Web server. When a Web browser requests a URL that points to a file within the CGI directory (e.g.,, then, instead of simply sending that file (/usr/local/apache/htdocs/cgi-bin/ to the Web browser, the HTTP server runs the specified script and passes the output of the script to the Web browser. That is, anything that the script sends to standard output is passed to the Web client instead of being shown on-screen in a terminal window.

As remarked above, the CGI standard defines how additional information passed with the request is passed to the script. For instance, if a slash and additional directory name(s) are appended to the URL immediately after the name of the script (in this example, /with/additional/path), then that path is stored in the PATH_INFO environment variable before the script is called. If parameters are sent to the script via an HTTP GET request (a question mark appended to the URL, followed by param=value pairs; in the example, ?and=a&query=string), then those parameters are stored in the QUERY_STRING environment variable before the script is called. If parameters are sent to the script via an HTTP POST request, they are passed to the script's standard input. The script can then read these environment variables or data from standard input and adapt to the Web browser's request.[7]


The following Perl program shows all the environment variables passed by the Web server:



printenv — a CGI program that just prints its environment

print "Content-type: text/plain\n\n";

for my $var ( sort keys %ENV ) {
 printf "%s = \"%s\"\n", $var, $ENV{$var};

If a Web browser issues a request for the environment variables at, a 64-bit Microsoft Windows web server running cygwin returns the following information:

 DOCUMENT_ROOT="C:/Program Files (x86)/Apache Software Foundation/Apache2.2/htdocs"
 HTTP_ACCEPT_ENCODING="gzip, deflate"
 HTTP_USER_AGENT="Mozilla/5.0 (Windows NT 6.1; WOW64; rv:5.0) Gecko/20100101 Firefox/5.0"
 PATH_TRANSLATED="C:\Program Files (x86)\Apache Software Foundation\Apache2.2\htdocs\foo\bar"
 SCRIPT_FILENAME="C:/Program Files (x86)/Apache Software Foundation/Apache2.2/cgi-bin/"
 SERVER_ADMIN="(server admin's email address)"
 SERVER_SOFTWARE="Apache/2.2.19 (Win32) PHP/5.2.17"

Some, but not all, of these variables are defined by the CGI standard. Some, such as PATH_INFO, QUERY_STRING, and the ones starting with HTTP_, pass information along from the HTTP request.

From the environment, it can be seen that the Web browser is Firefox running on a Windows 7 PC, the Web server is Apache running on a system that emulates Unix, and the CGI script is named cgi-bin/

The program could then generate any content, write that to standard output, and the Web server will transmit it to the browser.

The following are environment variables passed to CGI programs:

The program returns the result to the Web server in the form of standard output, beginning with a header and a blank line.

The header is encoded in the same way as an HTTP header and must include the MIME type of the document returned.[8] The headers, supplemented by the Web server, are generally forwarded with the response back to the user.

Here is a simple CGI program in Python along with the HTML that handles a simple addition problem.[9]

<!DOCTYPE html>
  <form action="add.cgi" method="POST">
   Enter two numbers to add:<br />
   First Number: <input type="text" name="num1" /><br />
   Second Number: <input type="text" name="num2" /><br />
   <input type="submit" value="Add" />

import cgi
import cgitb


print 'Content-Type:text/html' #HTML is following
print                          #Leave a blank line
print '<h1>Addition Results</h1>'
  print '<p>Sorry, we cannot turn your inputs into numbers (integers).</p>'
  return 1
print '<p>{0} + {1} = {2}</p>'.format(num1,num2,sum)

This Python CGI gets the inputs from the HTML and adds the two numbers together.


A Web server that supports CGI can be configured to interpret a URL that it serves as a reference to a CGI script. A common convention is to have a cgi-bin/ directory at the base of the directory tree and treat all executable files within this directory (and no other, for security) as CGI scripts. Another popular convention is to use filename extensions; for instance, if CGI scripts are consistently given the extension .cgi, the web server can be configured to interpret all such files as CGI scripts. While convenient, and required by many prepackaged scripts, it opens the server to attack if a remote user can upload executable code with the proper extension.

In the case of HTTP PUT or POSTs, the user-submitted data are provided to the program via the standard input. The Web server creates a subset of the environment variables passed to it and adds details pertinent to the HTTP environment.


CGI is often used to process inputs information from the user and produce the appropriate output. An example of a CGI program is one implementing a Wiki. The user agent requests the name of an entry; the Web server executes the CGI; the CGI program retrieves the source of that entry's page (if one exists), transforms it into HTML, and prints the result. The web server receives the input from the CGI and transmits it to the user agent. If the "Edit this page" link is clicked, the CGI populates an HTML textarea or other editing control with the page's contents, and saves it back to the server when the user submits the form in it.


Calling a command generally means the invocation of a newly created process on the server. Starting the process can consume much more time and memory than the actual work of generating the output, especially when the program still needs to be interpreted or compiled. If the command is called often, the resulting workload can quickly overwhelm the server.

The overhead involved in process creation can be reduced by techniques such as FastCGI that "prefork" interpreter processes, or by running the application code entirely within the web server, using extension modules such as mod_perl or mod_php. Another way to reduce the overhead is to use precompiled CGI programs, e.g. by writing them in languages such as C or C++, rather than interpreted or compiled-on-the-fly languages such as Perl or PHP, or by implementing the page generating software as a custom webserver module.

Several approaches can be adopted for remedying this:

The optimal configuration for any Web application depends on application-specific details, amount of traffic, and complexity of the transaction; these tradeoffs need to be analyzed to determine the best implementation for a given task and time budget.

See also


External links

This article is issued from Wikipedia - version of the 11/27/2016. The text is available under the Creative Commons Attribution/Share Alike but additional terms may apply for the media files.