Version 21 of Writing simple CGI applications using vanilla Tcl

Updated 2004-08-24 13:00:17 by schlenk

Purpose: describe for the gentle reader how one can do simple CGI applications with nothing up our sleeves...


First, here's a sample CGI script:


 #! /usr/tcl84/bin/tclsh

 proc generate_page {} {
        puts stdout "Content-type: text/html\n"
        puts stdout "<HTML>"
        puts stdout "<HEAD>"
        puts stdout "<TITLE>Wave to the world!</TITLE>"
        puts stdout "</HEAD>"
        puts stdout "<BODY>"
        puts stdout "Hello, world!" 
        puts stdout "</BODY></HTML>"
 }

 if {[catch { generate_page } err]} {
        puts stdout "Content-type: text/plain\n\n$err"
 }

Some key concepts:

  • The first line tells the web server what program to run to execute the script. Change this line to be the location of the tclsh executable on your system.
  • Your program should output a line containing the content type of the page. In the example, it's an HTML file.
  • The Content-type line MUST be followed by a blank line, otherwise you'll get an error message. Note that puts, by default, adds its own newline. The temptation is to specify two, but one is correct.
  • The remainder of the script outputs a web page (in this example).

Now, what do you do with it?

That's a bit tougher to answer. See, it all depends on how the http server was configured. The best thing to do is to contact the person who knows about the specific web server and ask.

"But", you ask, "what if I am the person who installed the server, and I have no idea what the server is expecting?"

Well, all I can do is suggest that you find a newsgroup, mailing list, or web forum that supports the server in question, and ask the kind people there what the default directories, naming conventions, etc. are.

A good place to start is http://www.equi4.com/259 .


The "#! /usr/tcl84/bin/tclsh" is more specific to Apache type of servers. Windows IIS 4.x and later does NOT use this, it uses a script map to control execution based on file extension names (e.g., *.cgi, *.cgt, *.tcl)

Yes - This is true - But the "#! /usr/tcl84/bin/tclsh" does not hurt the application - as it is seen as a comment by the Tcl Intrepreter when you execute it via IIS. We use both web environments systems here, the same code runs on Apache and IIS. But I do see you point that is can be dropped. (DB)

You might also want to consider using Don Libes cgi.tcl also - it can be very handy for, HTML Generation, forms and form manipulations. Additionally, I would recommend TimpleSQL if you want to CGI content into a database.


To do anything interesting with CGI's, though, you need to be able to *receive* data as well as send it, and that's where ncgi, cgi.tcl and company come in. CL finds it not-hard to receive CGI data "by hand", wonders why all the "puts stdout ..." above, rather than just "puts ..."


Category Internet