CGI
Contents
Running CGI scripts
If you want to provide interactive or dynamic information on your homepage, you can use CGI scripts. This CGI script will be executed whenever someone on the Net requests its URL.
We use Apache with suexec. Because of this, all your CGI scripts will be executed under your own user-ID. If you write insecure scripts, this could be (only) a problem for the data in your account!
A short (and secure) CGI Example
1. Create the file ~/public_html/cgi-bin/clock.pl:
#!/usr/bin/perl print "Content-Type: text/html\n\n"; print "Hello visitor from $ENV{REMOTE_ADDR}<BR>"; print "It is now ".localtime(time)."\n";
Note you may first have to create the cgi-bin directory.
2. Make sure that you have assigned the right permissions to your CGI script:
chmod 744 ~/public_html/cgi-bin/clock.pl
chmod 755 ~/public_html/cgi-bin
3. Now you can use your first CGI program by calling the address https://people.ee.ethz.ch/~YOURLOGINNAME/cgi-bin/clock.pl
Some points to note when writing CGI programs:
The CGI scripts run under your UID, and can therefore access all the files you can access. In other words: CGI scripts can be a large security hole if written carelessly. I suggest you take a long and careful look at the CGI Security FAQ.
While you can write CGIs in whatever computer language you want, the most popular is certainly Perl (see example above). You find several Perl courses in the Programming Area of the computing website.
Do not reinvent the wheel. Use CGI.pm when writing CGIs in Perl. Learn all about it by typing perldoc CGI.
CGIs do not necessarily have to be in the cgi-bin directory. They can be anywhere in your public_html directory or below if their name ends with the letters .cgi.
The most common error when writing the first CGI program is that people tend to forget that it must print the line "Content-Type: text/html" followed by two newlines. This line tells the Web server and also the Web browser what type of data the CGI script will create. In other words, if your CGI script was to output plain text instead of HTML code you would have to announce this with the line "Content-Type: text/plain".
Debugging CGI scripts is not easy. One place worth looking at is the error log file of the people.ee.ethz.ch Web server: /var/log/apache/error_log.people. If it simply states Premature end of script headers for the name of your CGI script, then there might also be an issue with the suexec wrapper - in this case you should also look into /var/log/apache/suexec.log.
Debugging Perl CGI scripts
If your CGI refuses to work you might want to put the following lines at the very start of your script. They will help to debug the beast as all error messages should be printed on your Web browser.
BEGIN{ my ($HDO)=0; print "Content-Type: text/plain\n\n"; umask 022; select(STDOUT); $| = 1; # make unbuffered close (STDERR); open (STDERR ,">&STDOUT") || die "Can't dup stdout"; map {print "$_: $ENV{$_}\n"} keys %ENV; print "\n\n"; };