eekim.com > Publications > CGI Developer's Guide > Chapter 2

Chapter 2: The Basics    (01)

<Next | Table of Contents | Previous>    (02)

A Simple CGI Program    (03)

You are going to write a CGI program called nameage.cgi that processes the name/age form. The data processing (what I like to call the "in-between stuff") is minimal. nameage.cgi simply decodes the input and displays the user's name and age. Although there is not much utility in such a tool, this demonstrates the most crucial aspect of CGI programming: input and output.    (04)

You use the same form as described previously, calling the fields name and age. For now, don't worry about robustness or efficiency; you solve the problem at hand using the simplest possible solution. The Perl and C solutions are shown in Listings 2.6 and 2.7, respectively.    (05)


Listing 2.6. nameage.cgi in Perl.    (06)


#!/usr/local/bin/perl
# nameage.cgi
require 'cgi-lib.pl'
&ReadParse(*input);
print "Content-Type: text/html\r\n\r\n";
print "<html> <head>\n";
print "<title>Name and Age</title>\n";
print "</head>\n";
print "<body>\n";
print "Hello, " . $input{'name'} . ". You are\n";
print $input{'age'} . " years old.<p>\n";
print "</body> </html>\n";    (07)

Listing 2.7. nameage.cgi in C.    (08)


/* nameage.cgi.c */
#include <stdio.h>
#include "cgi-lib.h"
int main()
{
  llist input;
  read_cgi_input(&input);
  printf("Content-Type: text/html\r\n\r\n");
  printf("<html> <head>\n");
  printf("<title>Name and Age</title>\n");
  printf("</head>\n");
  printf("<body>\n");
  printf("Hello, %s. You are\n",cgi_val(input,"name"));
  printf("%s years old.<p>\n",cgi_val(input,"age"));
  printf("</body> </html>\n");
}    (09)

Note these two programs are almost exactly equivalent. They both contain parsing routines that occupy only one line and handle all the input (thanks to the respective library routines). The output is essentially a glorified version of your basic Hello, world! program.    (010)

Try running the program by filling out the form and pressing the Submit button. Assuming you enter Eugene for name, and 21 for age, your result should resemble Figure 2.4.    (011)

Figure 2.4. The result of the CGI nameage.cgi    (012)

<Next | Table of Contents | Previous>    (013)

Copyright © 1997 Sams.Net Publishing    (014)