1) Customize Pages with CGI

CGI can show different pages to different users depending on user preferences.

Exercise:

1.1 Create a form that asks a user to input their name into a textfield and to choose a color from a selection of radio buttons. Create a CGI script that displays a page with a short message (e.g. "Thank you", name, "for your request") in the color which the user chose.

2) Environment Variables

#!/usr/bin/env python
#
######### CGI header #######################################
import cgi
print "Content-Type: text/html\n"
form = cgi.FieldStorage()

######### import the operating system module ###############
import os

########## HTML header ######################################
print """
<html> <head> <title>Environment Variables </title> </head>
<body> <h2>Here are all the environment variables:</h2>
"""

############ print the environment variables ########
keys = os.environ.keys()
keys.sort()
for item in keys:
    print item, ": ", os.environ[item], "<br>"

########## HTML footer ######################################
print """
</body></html>
"""

Exercises

2.1 Insert the code for printing environment variables into your CGI script from the previous exercise. In the HTML form first set the form method to GET, then to POST. You'll notice that some environment variables, such as CONTENT_LENGTH are only available for one of the two methods.

2.2 You can use CONTENT_LENGTH to increase the security of your CGI script (by ensuring that the user is not attempting to overload your script with large amounts of data). Insert an if statement into your script that prints a warning if os.environ["REQUEST_METHOD"] is set to POST and int(os.environ["CONTENT_LENGTH"]) is larger than 10. (Note: int() is used to convert the string value of the environment variable into a number. The value 10 is too small for most scripts. If you are going to use this in your project, you need to adjust the value.)

3) Security on CGI Pages

Because CGI scripts run on a server that is accessed by remote clients, there are security risks for the server!

Here are some security tips:

a) General tips

b) Check user input!

c) File handling

d) System calls (Using the os module)

e) Passwords

More information on security is available from this W3C page. Even though the CGI examples in section 6 of that page refer to Perl, the security problems for Python are similar.

Exercise

3.1 Apply all the security measures mentioned above under "b) Check user input" to your script from exercise 1.1. For example, check that neither name nor color are empty, check that the color is one of the radio button choices from your form, check that name contains only word characters, space or hyphen (-), and check that the name is not longer than 50 chars.
If your script encounters any security problem, print an error message and exit the script using sys.exit().