HTML Forms and CGI

The original and still most popular use for forms is in conjunction with CGI (Common Gateway Interface). In the CGI way of doing things, the data the user enters is sent to the web server, where a program processes the data and returns the results. In other words, all the data is processed on the server, not in the web browser.

Let's expand our earlier example to show how to incorporate CGI:

<FORM ACTION="/cgi-bin/">
favorite color: <INPUT name="favecolor">

which gives us

favorite color: (Form is not live)

Here's what the new pieces mean:

<FORM ACTION="/cgi-bin/">
ACTION tells the browser where to send the data for processing (more on that shortly). ACTION is required with every form, even forms that don't use CGI.

<INPUT name="favecolor">
We've added the NAME attribute. NAME identifies each field, "names" it so it can be referred to later.

This <INPUT ...> tag creates the "submit" button, which the user presses to send the form to the web server.

That's the basic set up for a CGI form, but what happens after the user presses Submit? Consider, for example, a simple newsletter subscription form. Here's the chain of events when the user hits "Submit":

  1. When the user presses Submit, the browser sends the form data to the web server.
  2. The web server launches the CGI program which was written to process this form.
  3. The CGI program does whatever it does with the data. The program might consult a database, perform calculations on the data, use the data to add the user to a mailing list, whatever the programmer wants it to do. Whatever else the program does, it generates a web page using HTML so the user can see the results of submitting the form.
  4. The CGI program passes the HTML back to the web server.
  5. The web server passes the HTML back to the browser.

So there are three pieces to the CGI process: the form on your web page, the web server, and the CGI program. This guide deals with the first part: how to use HTML to make a form. Your web administrator handles the web server, and for a good guide on how to write CGIs, visit some of the resources in the CGI > Tutorials category at the Google Directory.

Technically speaking there is no such thing as "a CGI". "CGI" is a standard protocol, not an actual implementation. However, it has become common to refer to a program which uses the CGI standard as "a CGI", and we will follow that custom here.

One of the reasons CGI is so popular is that the CGI program can be written in just about any programming language: C, C++, Perl (the most popular language for CGI), Visual Basic, etc. CGI was designed to allow great flexibility in processing the form data, while still allowing the results to be returned as HTML (or other formats, but HTML is the most popular).

Forms and Scripts >