CGI Basics

Do all the projects.

Complete all the Quizzes.

Instructional Video: Full Screen  Ipod Version

Websites that were helpful in the making this page:

What is CGI?

CGI stand for Common Gateway Interface.  CGI is what allows you to communicate with other scripts and programs that are on a server.

CGI allows us to send information to a program that is running on a server.  Typically we send data to the programs using Forms.

The data is sent to the program then parsed out then return to us in by sending a response back to our web browser.

FORMS

Picture taken from O'Reilly & Associates CGI Programming on the World Wide Web

This is a simple diagram of a simple CGI diagram.

 Form processing still provide most of all CGI use.

Display your first webpage using Python

First we need to place the python program in the right locations so it can be accessed via the web.
  • Place the program in your CGI directory (/cgi-bin/ on most unix machines)
  • Login via putty
  • > cd public_html
  • > cd cgi-bin
  • We now need to double check the location on pyton on the system
  • > whereis python
  • python: /usr/bin/python 
  • save a python programs as .cgi instead of .py when working with the web.
The first line of code is needed when accessing  python programs via the web remotely.  You need to place #! then the location of python on your system

The next command tells the browser how to render it.  Example Web, Txt, Excel, etc

Then, we need to write something to the screen

#!/usr/bin/python

# Required header that tells the browser how to render it
print "Content-Type: text/plain\n\n"

# Print a simple message to display
print "I just love this stuff!"

Save as python.cgi
Change permissions to: chmod 755 python.cgi
To access: http://web.niaccist.niacc.edu/~username/cgi-bin/python.cgi

Results:

Displaying your python operations on a webpage

#!/usr/bin/python

# Required header that tells the browser how to render it
print "Content-Type: text/plain\n\n"

firstName = "Steve"
lastName = "Miller"

# Print values to webpage
print "Hello %s %s" % (firstName, lastName)


Save as python2.cgi
Change permissions to: chmod 755 python2.cgi
To access: http://web.niaccist.niacc.edu/~username/cgi-bin/python2.cgi

If you forget to change permission you can get an error like below:

chmod 755 python2.cgi then click refresh

Web Results:

Now use logic and print where needed

#!/usr/bin/python

# Print the required header that tells the browser how to render the text.
print "Content-Type: text/plain\n\n"

# Initialize a few variables.
first_name = "Steve"
last_name = "Miller" 
age = 39

# Test for name.
if (first_name and last_name):
    print "Hello,", first_name, last_name
    print "It is good to see you, Mr.", last_name
elif first_name:
    print "Hello,", first_name
else:
    print "Who are you?"

    # Test for age.
if (age >= 21):
    print "You can drink!"
else:
    print "No drinks for you!"

Save as python3.cgi
Change permissions to: chmod 755 python3.cgi
To access: http://web.niaccist.niacc.edu/~username/cgi-bin/python3.cgi

Note you can test your program on command line before you do via the web.  The advantage of command line is it gives a better description of any errors.  If it runs fine on command line and not via the web, check the permissions.

> python python3.cgi
Content-Type: text/plain


Hello, Steve Miller
It is good to see you, Mr. Miller
You can drink!


Web Results:


Call a function and display the results to the webpage

#!/usr/bin/python

# Print the required header that tells the browser how to render the text.
print "Content-Type: text/plain\n\n"

# Define a global variable gender = "female".
gender = "female"

# Define a function.
def display_vars (first_name, last_name, age):
   print (first_name, last_name, age, gender)

# Define a function that calls 'display_vars' with intended local 'gender'.
def go_display():
   gender = "male"
   display_vars("Steve", "Miller", 44)

# Call the function 'go_display'.
go_display()

Save as python4.cgi
Change permissions to: chmod 755 python4.cgi
To access: http://web.niaccist.niacc.edu/~username/cgi-bin/python4.cgi


Creating forms


The form and /form surround the definition of the form. Within the form element, there are two frequently used attributes: method and action.

Method tells the browser how to format the data packet before shipping it to the server for processing.

Using post tells the browser to format the data as a separate packet.

The alternative is the get method. Using get tells the browser to attach the data names and values to the end of the URL and pass it to the server. This is the mechanism many search engines use. (Go to Google, put in some keywords and start a search. Check out the URL in the Location or Address field at the top of the browser window after you hit the search button. This is a get.) While the get method is very fast, the downside is that you are limited to as little as 256 characters on the URL call, so the amount of data you can pass is VERY limited. Use post whenever possible.

action tells the browser the address of the CGI script to execute when the Submit button is pressed. (We will talk more about the Submit button in a minute.)

If you really need to have a CGI script and your ISP will not host them (and some providers do not), get into Google and search for free form hosting services. There are quite a few out there and each will have directions on what to do to host on their server.

Forms

Using form elements

A form is pretty worthless without a place to enter data. This page shows many different ways to collect data from the viewer. Each of these elements can be added between the form and /form to generate the finished piece.

We will start with a few examples of the input element. Input is a very versatile way to collect a lot of different types of data. Go ahead and try any of these on the page that you would like, they are all functioning. Changes to these fields will affect nothing.


<input type="text" name="namebox" value="Enter your first name" size="25" maxlength="30" />  

The text input field is used to collect short, textual answers, generally one line in length. The value attribute is what is shown in the field when the page is generated. The size attribute tells the browser how long to make the field and the maxlength attribute states the maximum size of the input in characters.


<input type="password" name="passinput" size="25" maxlength="30" />  

The password input field is used for input of a password. The only difference between the type of text and the type of password is that the password is automatically displayed as asterisks in the window.


<input type="radio" name="multiplechoice" value="A" />A
<input type="radio" name="multiplechoice" value="B" />B
<input type="radio" name="multiplechoice" value="C" checked="checked" />C
<input type="radio" name="multiplechoice" value="D" />D
 
 

A B C D

The radio buttons are used to select a single value for a given set of unique selections. For example, most multiple choice exams can easily be converted to radio buttons for the web.

Notice that all of these buttons have the same name. This is how the browser knows what to clear when a button is pressed. For example, if a viewer selected the letter D with the name of multiplechoice, the browser knows to find all other elements with a name of multiplechoice and clear their content.


<input type="checkbox" name="banana" value="banana" checked="checked" /> Banana
<input type="checkbox" name="net" value="hairnet" /> Hair Nets
<input type="checkbox" name="laces" value="shoelace" checked="checked" /> Shoe laces
 
 

Banana
Hair net
Shoe laces
 

The checkbox is used to select multiple items from a list. Unlike the radio button, each checkbox is a separate field with its own name.


<select name="selmenu">
<optgroup label="Hard woods">
<option value="Mahogany">Mahogany</option>
<option value="Maple">Maple</option>
<option value="Cherry">Cherry</option><optgroup>
<optgroup label="Soft woods">
<option value="Pine">Pine</option>
<option value="Fir">Fir</option><optgroup>
</select">
 

<select name="selmenu" size="2" multiple="multiple">
<optgroup label="Hard woods">
<option value="Mahogany">Mahogany</option>
<option value="Maple">Maple</option>
<option value="Cherry">Cherry</option><optgroup>
<optgroup label="Soft woods">
<option value="Pine">Pine</option>
<option value="Fir">Fir</option><optgroup>
</select">
 

The select menu allows for a pull-down-style menu for selecting the possible input. Each selection in the list is created using an option and /option tag. For longer lists, items can be grouped into submenus using the optgroup and /optgroup tags. The user clicks on the menu to activate it and then selects the appropriate response and clicks on it with the mouse. There are two examples of the same select menu above, one with the default settings and one with a menu size of 2 and multiple selections allowed. (To make multiple selections, hold down the Control or Command key.)


<textarea name="bigtext" rows="3" cols="25">
This text appears in the textarea when it is displayed.
</textarea>
 

The textarea allows for input of large amounts of text. In fact, if the text does not fit in the allowed area, scroll bars will be added for you.


<input type="hidden" name="hiddenfield" value="Top secret stuff" />  

The hidden field is used to store things that you want to pass to the server but you do not want the user to see or change. Examples of this could be the address for the To: field of the email, the name of the page that request is coming from, or information that you asked for on earlier pages.


<input type="submit" />
<input type="submit" value=" Send your request " />
 

The submit button triggers the passing of data from the form to the script that processes it. We have two examples here, one that shows the default look of a submit button and one that we added a value. The value is used as the text on the button. You can also use an image as a submit button by surrounding an img tag with the button and /button tag. It looks like this:

<button type="submit" name="submit" value="submit">
<img ...>
</button>


<input type="reset" />  

The reset button clears all of the fields in the form back to their original state. Like the submit, you can use the value attribute to define your own phrase on the button. You can use the button tag, like the submit above, to create a reset button using an image as the button.

HTML form

We can call our python script from a simple html web page with a form.  Typically located in the directory:
  • public_html
<html>
<title>HTML form calling python cgi </title>
<body>
<h1>HTML form calling python cgi</h1>
<form method="POST" action="cgi-bin/process.cgi">
    <p>Your first name: <input type="text" name="firstname">
    <p>Your last name: <input type="text" name="lastname">
    <p>Click here to submit form: <input type="submit" value="Enter">
 </form>
</body>
</html>

Save as python.html in public_html directory
Change permissions to: chmod 744 python.html
To access: http://web.niaccist.niacc.edu/~username/python.html

Web Results:


  • To render HTML webpages using HTML we need to change the header to:
  • print "Content-Type: text/html\n\n"

Or we can generate the form in a python cgi program.  Located in cgi-bin directory

#!/usr/bin/python

# Print the required header that tells the browser how to render the text.
print "Content-Type: text/html\n\n"

print """<html>
<title>HTML form calling python cgi </title>
<body>
<h1>HTML form calling python cgi</h1>
<form method="POST" action="process.cgi">
    <p>Your first name: <input type="text" name="firstname">
    <p>Your last name: <input type="text" name="lastname">
    <p>Click here to submit form: <input type="submit" value="Enter">
</form>
</body>
</html>"""

Save as python5.cgi
Change permissions to: chmod 755 python5.cgi
To access: http://web.niaccist.niacc.edu/~username/cgi-bin/python5.cgi

Web Results:

Process html form python program

#!/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('firstname')
last_name  = form.getvalue('lastname')

print "Content-type:text/html\r\n\r\n"
print "<html>"
print "<head>"
print "<title>Hello - Python CGI Program</title>"
print "</head>"
print "<body>"
print "<h2>Hello %s %s</h2>" % (first_name, last_name)
print "</body>"
print "</html>"

Save as process.cgi
Change permissions to: chmod 755 process.cgi
To access: http://web.niaccist.niacc.edu/~username/cgi-bin/process.cgi

If you call it directly no name value pairs are sent and you receive the word  "None" instead.Web Results:


Now call it from the python.html or python5.cgi
Then click Enter or hit Enter Key

 
Web Results:




Sending Name/Value pairs using URL/Get request

We start with:
  •  http://web.niaccist.niacc.edu/~username/cgi-bin/process.cgi
  • Next add "?"
  • Next add name value pairs "firstname=Steve&lastname=Miller"
  • Now test it but puttting it all together and enter it into a web browser url (address field)
  • http://web.niaccist.niacc.edu/~username/cgi-bin/process.cgi?firstname=Steve&lastname=Miller

Web Results:

Calling a Get with a Link

You can take the URL string an format it as a link.  This helps when you don't want a big form on the page and want something compact.

<a href="http://web.niaccist.niacc.edu/~username/cgi-bin/process.cgi?firstname=Steve&lastname=Miller">Send Name</a>

Applied:

Send Name


Form  Validation

Now lets check to see if the first and last name were entered.  If not display form enter.

#!/usr/bin/python

# Import modules for CGI handling
import cgi, cgitb

print "Content-type:text/html\r\n\r\n"

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

if(form.has_key("firstname") and form.has_key("lastname")):

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

   print "<html>"
   print "<head>"
   print "<title>Hello - Python CGI Program</title>"
   print "</head>"
   print "<body>"
   print "<h2>Hello %s %s</h2>" % (first_name, last_name)
   print "</body>"
   print "</html>"
else:

   print """<html>
<title>HTML form calling python cgi </title>
<body>
<h1>Your name was missing please reenter</h1>
<form method="POST" action="processvalidation.cgi">
    <p>Your first name: <input type="text" name="firstname">
    <p>Your last name: <input type="text" name="lastname">
    <p>Click here to submit form: <input type="submit" value="Enter">
</form>
</body>
</html>"""

Save as processvalidation.cgi
Change permissions to: chmod 755 processvalidation.cgi

Call without names: http://web.niaccist.niacc.edu/~milleste/cgi-bin/processvalidation.cgi
Web Results:

Call with names:
http://web.niaccist.niacc.edu/~milleste/cgi-bin/processvalidation.cgi?firstname=Steve&lastname=Miller

CGI Environment Variables

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

Variable Name Description
CONTENT_TYPE The data type of the content. Used when the client is sending attached content to the server. For example file upload etc.
CONTENT_LENGTH The length of the query information. It's available only for POST requests
HTTP_COOKIE Return the set cookies in the form of key & value pair.
HTTP_USER_AGENT The User-Agent request-header field contains information about the user agent originating the request. Its name of the web browser.
PATH_INFO The path for the CGI script.
QUERY_STRING The URL-encoded information that is sent with GET method request.
REMOTE_ADDR The IP address of the remote host making the request. This can be useful for logging or for authentication purpose.
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.
REQUEST_METHOD The method used to make the request. The most common methods are GET and POST.
SCRIPT_FILENAME The full path to the CGI script.
SCRIPT_NAME The name of the CGI script.
SERVER_NAME The server's hostname or IP Address
SERVER_SOFTWARE The name and version of the software the server is running.

 

Here is 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 "<font size=+1>Environment</font><br>";
for param in os.environ.keys():
print "<b>%20s</b>: %s<br>" % (param,os.environ[param])

Save as env.cgi
Change permissions to: chmod 755 env.cgi

Call: http://web.niaccist.niacc.edu/~milleste/cgi-bin/env.cgi
Web Results: