Common Gateway Interface (CGI) is a very outdated method to handel user requests. The idea is that it models the client-server interaction as client want to execute some scripts on server (since you want dynamic content based on user input, such as google query). So, CGI does exactly that, given URL (included query string in URL), launch a new process to execute some script, passing the query string in URL as argument. CGI is a specification on how to invoke scripts and pass arguments to scripts. For example if you click the following html
<A HREF="http://www.jdon.com/cgi-bin/getdate">Display the Date</A>
It will launch a script like the following
#!/bin/sh
echo Content-type: text/plain
echo
/bin/date
and user will see
Content-type: text/plain
Tue Oct 25 16:15:57 EDT 1994
Apache limits every script that is executable by the client must be under /cgi-bin/
, which is why you will see /cgi-bin/xxx
on your URL.
Rules:
If additional path like /with/additional/path
: store them in env variable PATH_INFO
If found query string like ?and=a&query=string
: store them in QUERY_STRING
If request is of type POST
, then pass into script's stdin
One bit of the CGI spec that is still in use everywhere is the standard method of passing URL parameters, e.g. http://dpaste.com/?title=from%20Quora
CGI was the first popular standard that defined how to make executables on a server respond to web requests; it specifies a web server interface for them to use. A lot of the first ones were written in C because hey, why not. The idea of "web scripting" did not exist when CGI was created; CGI itself was the catalyst that allowed that to happen.
Mostly what replaced CGI in the next generation of web applications was Apache web server modules supporting specific languages that proved to be (or were developed to be) useful for the web - mod_perl
, mod_php
, mod_python
, python WSGI
, java servlets
, etc.
Here we provide a python script in CGI format
add.html
<!DOCTYPE html>
<html></html>
add.cgi
#!/usr/bin/env python3
import cgi, cgitb
cgitb.enable()
input_data = cgi.FieldStorage()
print('Content-Type: text/html') # HTML is following
print('') # Leave a blank line
print('<h1>Addition Results</h1>')
try:
num1 = int(input_data["num1"].value)
num2 = int(input_data["num2"].value)
except:
print('<output>Sorry, the script cannot turn your inputs into numbers (integers).</output>')
raise SystemExit(1)
print('<output>{0} + {1} = {2}</output>'.format(num1, num2, num1 + num2))
This Python 3 CGI program gets the inputs from the HTML and adds the two numbers together.
Drawbacks:
very insecure ways to execute script
very inefficient since every request need to spawn a new process
Table of Content