Simplest CGI Program
Here’s the source code for your first CGI program. It’s so simple it doesn’t even need to use the CGI.pm module.
# howdy--the easiest of CGI programs print <<END_of_Multiline_Text; Content-type: text/html <HTML> <HEAD> <TITLE>Hello World</TITLE> </HEAD> <BODY> <H1>Greetings, Terrans!</H1> </BODY> </HTML> END_of_Multiline_Text
Each and every time this program is called, it displays exactly the same thing. It’s not particularly dynamic, or interesting. But we’ll spice it up later.
This little program contains just one statement: a call to the
print function. That somewhat funny looking
argument is a here document. It starts with two
less-than signs and a word that we’ll call the end
token. Although this may look like I/O redirection,
it’s really just a convenient way to quote a multiline string.
The string begins on the next line and continues up to a line
containing the end token, which must stand by itself at the start of
the line. The end token must not have any surrounding whitespace and
the line it’s on must be terminated with a newline. Here
documents are especially handy for generating HTML.
The first part in that long string is arguably the most important:
the Content-Type line identifies the type of output you’re generating. It’s immediately followed by a blank line, which must not contain any spaces or tabs. Most beginners’ first CGI programs fail because they forget that blank line, which separates the header (somewhat like a mail header) from an optional ...
Become an O’Reilly member and get unlimited access to this title plus top books and audiobooks from O’Reilly and nearly 200 top publishers, thousands of courses curated by job role, 150+ live events each month,
and much more.
Read now
Unlock full access