Writing a CGI Script

Problem

You want to write a CGI script to process the contents of an HTML form. In particular, you want to access the form contents, and produce valid output in return.

Solution

A CGI script is a server-side program launched by a web server to generate a dynamic document. It receives encoded information from the remote client (user’s browser) via STDIN and environment variables, and it must produce a valid HTTP header and body on STDOUT. The standard CGI module, shown in Example 19.1, painlessly manages the encoding of input and output.

Example 19-1. hiweb

#!/usr/bin/perl -w
# hiweb - load CGI module to decode information given by web server
use strict;

use CGI qw(:standard escapeHTML);

# get a parameter from a form
my $value = param('PARAM_NAME');

# output a document
print header(), start_html("Howdy there!"),
      p("You typed: ", tt(escapeHTML($value))),
      end_html();

Discussion

CGI is just a protocol, a formal agreement between a web server and a separate program. The server encodes the client’s form input data, and the CGI program decodes the form and generates output. The protocol says nothing regarding which language the program must be written in; programs and scripts that obey the CGI protocol have been written in C, shell, Rexx, C++, VMS DCL, Smalltalk, Tcl, Python, and (of course) Perl.

The full CGI specification lays out which environment variables hold which data (such as form input parameters) and how it’s all encoded. In theory, it should be easy to follow ...

Get Perl Cookbook now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.