Today we started with this exercise: Write a CGI program in Python that can update a counter at the user's request. The counter goes up and down by one. The basic outline of the interface is like this: +---------------------------------------+ | The counter is now: .......... | | | | Press [here] to go up. | | | | Press [here] to go down. | +---------------------------------------+ The first [here] is a link, the second is a button. When you're done e-mail the code to: dgerman@indiana.edu Now let's look at the solution. Let's start with this: #!/usr/bin/python import cgi print "Content-type: text/html\n\n" (counter, message, action) = ("", "", "") d = cgi.FieldStorage() if d.has_key("counter"): counter = d["counter"].value if d.has_key("message"): message = d["message"].value if d.has_key("action"): action = d["action"].value if message: if action == "up": counter = str(int(counter) + 1) else: counter = str(int(counter) - 1) message = "Your new counter value is: " + counter else: counter = 0 message = "Welcome, your counter is: " + str(counter) print """
%s

Press to go up.

Press to go down.

""" % (message, counter, message) But where's the link, and what about the labels on the buttons? So here's the final version: #!/usr/bin/python import cgi print "Content-type: text/html\n\n" (counter, message, action) = ("", "", "") d = cgi.FieldStorage() if d.has_key("counter"): counter = d["counter"].value if d.has_key("message"): message = d["message"].value if d.has_key("action"): action = d["action"].value if message: if action == "up": counter = str(int(counter) + 1) else: counter = str(int(counter) - 1) message = "Your new counter value is: " + counter else: counter = 0 message = "Welcome, your counter is: " + str(counter) print """
%s

Press here to go up.

Press to go down.

""" % (message, counter, message, counter, message) Now let's talk about PHP. PHP is a different way of writing CGI scripts. The setup is a bit different: a) PHP scripts have a .php extension b) they are located in ~/apache/htdocs c) but they serve the same purpose and do exactly what CGI/Python (or Perl) does Proof:

Press here to go up.

Press to go down.

So the approach is much simplified in PHP.