Unique Field NamesΒΆ

Suppose we have this HTML form which submits a field named name to a python CGI script named process_form.py:

<form method="get" action="process_form.py">
Name: <input type="text" name="name">
<input type="submit" value="Submit">

This is the process_form.py script:

#!/usr/bin/env python
import cgi
form = cgi.FieldStorage() # instantiate only once!
name = form.getfirst('name', 'empty')

# Avoid script injection escaping the user input
name = cgi.escape(name)

print """\
Content-Type: text/html\n
<p>The submitted name was "%s"</p>
""" % name

The cgi.FieldStorage.getfirst() method returns the first value of the named field or a default or None if no field with that name was submited or if it is empty. If there is more than one field with the same name only the first will be returned.

If the HTML form method is changed from get to post the process_form.py script will be the same.

If the user inputed data is to be shown in a HTML document then it is necessary to escape it from HTML tags or else everything inside < > will be interpreted by the HTML parser including javascript code like

<script type="text/javascript"> malicious code here </script>

The cgi.escape() function will transform the above into safe HTML text:

&lt;script type="text/javascript"&gt; malicious code here &lt;/script&gt;

This is useful not only to prevent script injection but also to make it possible to display HTML source code as has just been done above.