WEB DEVELOPER SITE
PHP7
 

Python - CGI Programming


Common Gateway Interface, or CGI, is a set of standards that define how information is exchanged between the web server and a custom script.

What is CGI?

  • The Common Gateway Interface, or CGI, is a standard for external gateway programs to interface with information servers such as HTTP servers.

  • The current version is CGI/1.1 and CGI/1.2 is under progress.

Web Browsing

In this chapter concept of CGI when you click a hyper link to browse a particular web page or URL.
  • Your browser contacts the HTTP web server and demands for the URL, i.e., filename.

  • Web Server parses the URL and looks for the filename. If it finds that file then sends it back to the browser, otherwise sends an error message indicating that you requested a wrong file.

  • Web browser takes response from web server and displays either the received file or error message.

HTTP server so that whenever a file in a certain directory is requested that file is not sent back; instead it is executed as a program, and whatever that program outputs is sent back for your browser to display. These CGI programs can be a Python Script, PERL Script, Shell Script, C or C++ program, etc.

Web Server Support and Configuration

All the CGI Programs to be executed by the HTTP server are kept in a pre-configured directory. This directory is called CGI Directory and by convention it is named as /var/www/cgi-bin.

<Directory "/var/www/cgi-bin">
    AllowOverride None
    Options ExecCGI
    Order allow,deny
    Allow from all
</Directory>

<Directory "/var/www/cgi-bin">
Options All
</Directory>

First CGI Program

running your CGI program, make sure you have change mode of file using chmod 755 hello.py UNIX command to make file executable.
#!/usr/bin/python

print "Content-type:text/html\r\n\r\n"
print '<html>'
print '<head>'
print '<title>Hello Word - First CGI Program</title>'
print '</head>'
print '<body>'
print '<h2>Hello Word! This is my first CGI program</h2>'
print '</body>'
print '</html>'
If you click hello.py, then this produces the following output

Hello Word! This is my first CGI program


There is one important and extra feature available which is first line to be printed Content-type:text/html\r\n\r\n.

HTTP Header

The line Content-type:text/html\r\n\r\n is part of HTTP header which is sent to the browser to understand the content. All the HTTP header will be in the following form

HTTP Field Name: Field Content

For Example
Content-type: text/html\r\n\r\n
Sr.No. Header & Description
1

Content-type:

A MIME string defining the format of the file being returned. Example is Content-type:text/html

2

Expires: Date

The date the information becomes invalid. It is used by the browser to decide when a page needs to be refreshed. A valid date string is in the format 01 Jan 1998 12:00:00 GMT.

3

Location: URL

The URL that is returned instead of the URL requested. You can use this field to redirect a request to any file.

4

Last-modified: Date

The date of last modification of the resource.

5

Content-length: N

The length, in bytes, of the data being returned. The browser uses this value to report the estimated download time for a file.

6

Set-Cookie: String

Set the cookie passed through the string

CGI Environment Variables

All the CGI programs have access to the following environment variables. These variables play an important role while writing any CGI program.

Sr.No. Variable Name & Description
1

CONTENT_TYPE

The data type of the content. Used when the client is sending attached content to the server. For example, file upload.

2

CONTENT_LENGTH

The length of the query information. It is available only for POST requests.

3

HTTP_COOKIE

Returns the set cookies in the form of key & value pair.

4

HTTP_USER_AGENT

The User-Agent request-header field contains information about the user agent originating the request. It is name of the web browser.

5

PATH_INFO

The path for the CGI script.

6

QUERY_STRING

The URL-encoded information that is sent with GET method request.

7

REMOTE_ADDR

The IP address of the remote host making the request. This is useful logging or for authentication.

8

REMOTE_HOST

The fully qualified name of the host making the request. If this information is not available, then REMOTE_ADDR can be used to get IR address.

9

REQUEST_METHOD

The method used to make the request. The most common methods are GET and POST.

10

SCRIPT_FILENAME

The full path to the CGI script.

11

SCRIPT_NAME

The name of the CGI script.

12

SERVER_NAME

The server's hostname or IP Address

13

SERVER_SOFTWARE

The name and version of the software the server is running.

here small CGI program to list out all the CGI variables
#!/usr/bin/python

import os

print "Content-type: text/html\r\n\r\n";
print "Environment<\br>";
for param in os.environ.keys():
   print "%20s: %s<\br>" % (param, os.environ[param])

GET and POST Methods

Most of browser uses two methods two pass this information to web server. These methods are GET Method and POST Method.

Passing Information using GET method

The GET method sends the encoded user information appended to the page request. The page and the encoded information are separated by the ? character as followsc

http://www.test.com/cgi-bin/hello.py?key1=option1&key2=option2

The GET method has size limitation: only 1024 characters can be sent in a request string. The GET method sends information using QUERY_STRING header and will be accessible in your CGI Program through QUERY_STRING environment variable.

Simple URL Example:Get Method

Here is a simple URL, which passes two values to hello_get.py program using GET method.

/cgi-bin/hello_get.py?first_name=Hello&last_name=Welookups

hello_get.py script to handle input given by web browser. We are going to use cgi module

#!/usr/bin/python

# Import modules for CGI handling 
import cgi, cgitb 

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Get data from fields
first_name = form.getvalue('first_name')
last_name  = form.getvalue('last_name')

print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Hello - Second CGI Program</title>"
print "</head>"
print "<body>"
print "<h2>Hello %s %s</h2>" % (first_name, last_name)
print "</body>"
print "</html>"
This would generate the following result

Hello Welookups

Simple FORM Example:GET Method

This example passes two values using HTML FORM and submit button. We use same CGI script hello_get.py to handle this input.

<form action = "/cgi-bin/hello_get.py" method = "get">
First Name: <input type = "text" name = "first_name">  <br />

Last Name: <input type = "text" name = "last_name" />
<input type = "submit" value = "Submit" />
</form>

Here is the actual output of the above form, you enter First and Last Name and then click submit button to see the result.

First Name:
Last Name:

Passing Information Using POST Method

This message comes into the CGI script in the form of the standard input. Below is same hello_get.py script which handles GET as well as POST method.
#!/usr/bin/python

# Import modules for CGI handling 
import cgi, cgitb 

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Get data from fields
first_name = form.getvalue('first_name')
last_name  = form.getvalue('last_name')

print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Hello - Second CGI Program</title>"
print "</head>"
print "<body>"
print "<h2>Hello %s %s</h2>" % (first_name, last_name)
print "</body>"
print "</html>"
We use same CGI script hello_get.py to handle this input.
<form action = "/cgi-bin/hello_get.py" method = "post">
First Name: <input type = "text" name = "first_name"><br />
Last Name: <input type = "text" name = "last_name" />

<input type = "submit" value = "Submit" />
</form>

Here is the actual output of the above form. You enter First and Last Name and then click submit button to see the result.

First Name:
Last Name:

Passing Checkbox Data to CGI Program

Checkboxes are used when more than one option is required to be selected.

Here is example HTML code for a form with two checkboxes −

<form action = "#" method = "POST" target = "_blank">
<input type = "checkbox" name = "maths" value = "on" /> Home
<input type = "checkbox" name = "physics" value = "on" /> Schools
<input type = "submit" value = "Select Place" />
</form>

Below is checkbox.cgi script to handle input given by web browser for checkbox button.

#!/usr/bin/python

# Import modules for CGI handling 
import cgi, cgitb 

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Get data from fields
if form.getvalue('Home'):
   home_flag = "ON"
else:
   home_flag = "OFF"

if form.getvalue('Schools'):
   schools_flag = "ON"
else:
   schools_flag = "OFF"

print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Checkbox - Third CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> CheckBox Maths is : %s</h2>" % home_flag
print "<h2> CheckBox Physics is : %s</h2>" % schools_flag
print "</body>"
print "</html>"

Passing Radio Button Data to CGI Program

Radio Buttons are used when only one option is required to be selected.

Here is example HTML code for a form with two radio buttons −

<form action = "/cgi-bin/radiobutton.py" method = "post" target = "_blank">
<input type = "radio" name = "place" value = "home" /> Home
<input type = "radio" name = "place" value = "schools" /> Schools
<input type = "submit" value = "Select Place" />
</form>

The result of this code is the following form −

Home Schools

Below is checkbox.cgi script to handle input given by web browser for checkbox button.

#!/usr/bin/python

# Import modules for CGI handling
import cgi, cgitb

# Create instance of FieldStorage
form = cgi.FieldStorage()

# Get data from fields
if form.getvalue('homes'):
    home_flag = "ON"
else:
    home_flag = "OFF"

if form.getvalue('physics'):
    schools_flag = "ON"
else:
    schools_flag = "OFF"

print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Checkbox - Third CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> CheckBox Home is : %s</h2>" % home_flag
print "<h2> CheckBox Schools is : %s</h2>" % schools_flag
print "</body>"
print "</html>"

Passing Text Area Data to CGI Program

TEXTAREA element is used when multiline text has to be passed to the CGI Program.

Here is example HTML code for a form with a TEXTAREA box

<form action = "/cgi-bin/textarea.py" method = "post" target = "_blank">
<textarea name = "textcontent" cols = "40" rows = "4">
Type your text here...
</textarea>
<input type = "submit" value = "Submit" />
</form>

The result of this code is the following form −

Below is textarea.cgi script to handle input given by web browser −

#!/usr/bin/python

# Import modules for CGI handling 
import cgi, cgitb 

# Create instance of FieldStorage 
form = cgi.FieldStorage() 

# Get data from fields
if form.getvalue('textcontent'):
   text_content = form.getvalue('textcontent')
else:
   text_content = "Not entered"

print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>";
print "<title>Text Area - Fifth CGI Program</title>"
print "</head>"
print "<body>"
print "<h2> Entered Text Content is %s</h2>" % text_content
print "</body>"