About
Common Gateway Interface (CGI) is the oldest interface, and is supported by nearly every web server out of the box.
The web server will:
- parse the HTTP request into environment variable
- call an cgi-compatible executable:
- located by the URL path
- passing the HTTP request in environment variables
What is a cgi-compatible executable?
The executable is called a cgi-compatible executable if it:
- takes into account the request env variables
- and returns a HTTP response in its standard output
Any script (written in php, python, bash, ..) can be an a cgi-compatible executable.
Example
Php
This section shows how to use Php as a CGI script.
The web server would be configured to call the php-cgi executable.
For instance, you could:
- write the below php script hello-world.php in the root directory of your web server (supporting cgi and php)
- call it at http://127.0.0.1/hello-world.php
<html>
<head>
<title>PHP Test</title>
</head>
<body>
<?php echo '<p>Hello World</p>'; ?>
</body>
</html>
Python
- You may need to save this code with a .py or .cgi extension.
- Additionally, this file may also need to be in a cgi-bin folder, for security reasons.
#!/usr/bin/env python
# -*- coding: UTF-8 -*-
# cgitb enable debugging
# nice call trace vs “Internal Server Error”
import cgitb
cgitb.enable()
print "Content-Type: text/plain;charset=utf-8"
print
print "Hello World!"
Specification
URL / URI
The URL takes this specific form
<scheme>://<host>:<port>/<path>?<query>
where:
- path is the path of the script to call
- query is available in the env variable QUERY_STRING
Request
Environment variables 1) are used to pass data about the http request from the server to the script.
- AUTH_TYPE
- CONTENT_LENGTH
- CONTENT_TYPE
- GATEWAY_INTERFACE
- HTTP_*
- PATH_INFO
- PATH_TRANSLATED
- QUERY_STRING
- REMOTE_ADDR
- REMOTE_HOST
- REMOTE_IDENT
- REMOTE_USER
- REQUEST_METHOD
- SCRIPT_NAME
- SERVER_NAME
- SERVER_PORT
- SERVER_PROTOCOL
- SERVER_SOFTWARE
Response
A script will return the response via the standard output file descriptor 2)
The output may have one of the following format:
- Non-parsed Header: The script returns a original HTTP response message as specified by the HTTP specification.
- Parsed Header: The script returns a CGI response message. 3)
Performance
Programs using CGI to communicate with their web server need to be started by the server for every request. So, every request starts a new process (for python, a new Python interpreter) – which takes some time to start up – thus making the whole interface only usable for low load situations.
FastCGI tries to solve this shortcoming by loading the code into memory and making the script wait for a second request, making the process faster.