Uh-oh, it looks like your Internet Explorer is out of date.

For a better shopping experience, please upgrade now.

CGI Programming with Perl

CGI Programming with Perl

4.0 4
by Scott Guelich, Shishir Gundavaram, Gunther Birznieks

See All Formats & Editions

Programming on the Web today can involve any of several technologies, but the Common Gateway Interface (CGI) has held its ground as the most mature method—and one of the most powerful ones—of providing dynamic web content. CGI is a generic interface for calling external programs to crunch numbers, query databases, generate customized graphics, or perform


Programming on the Web today can involve any of several technologies, but the Common Gateway Interface (CGI) has held its ground as the most mature method—and one of the most powerful ones—of providing dynamic web content. CGI is a generic interface for calling external programs to crunch numbers, query databases, generate customized graphics, or perform any other server-side task. There was a time when CGI was the only game in town for server-side programming; today, although we have ASP, PHP, Java servlets, and ColdFusion (among others), CGI continues to be the most ubiquitous server-side technology on the Web.CGI programs can be written in any programming language, but Perl is by far the most popular language for CGI. Initially developed over a decade ago for text processing, Perl has evolved into a powerful object-oriented language, while retaining its simplicity of use. CGI programmers appreciate Perl's text manipulation features and its CGI.pm module, which gives a well-integrated object-oriented interface to practically all CGI-related tasks. While other languages might be more elegant or more efficient, Perl is still considered the primary language for CGI.CGI Programming with Perl, Second Edition, offers a comprehensive explanation of using CGI to serve dynamic web content. Based on the best-selling CGI Programming on the World Wide Web, this edition has been completely rewritten to demonstrate current techniques available with the CGI.pm module and the latest versions of Perl. The book starts at the beginning, by explaining how CGI works, and then moves swiftly into the subtle details of developing CGI programs.Topics include:

  • Incorporating JavaScript for form validation
  • Controlling browser caching
  • Making CGI scripts secure in Perl
  • Working with databases
  • Creating simple search engines
  • Maintaining state between multiple sessions
  • Generating graphics dynamically
  • Improving performance of your CGI scripts

Editorial Reviews

Explains how to use the common gateway interface (CGI) to create and deliver dynamic content on the web. The second edition has been rewritten to demonstrate current techniques available with the CGI.pm module and the latest versions of Perl. Annotation c. Book News, Inc., Portland, OR (booknews.com)

Product Details

O'Reilly Media, Incorporated
Publication date:
Edition description:
Second Edition
Product dimensions:
7.00(w) x 9.19(h) x 1.12(d)

Read an Excerpt

Chapter 8: Security

The Importance of Web Security

Many CGI developers do not take security as seriously as they should. So before we look at how to make CGI scripts more secure, let's look at why we should worry about security in the first place.

  1. On the Internet, your website represents your public image. If your web pages are unavailable or have been vandalized, that affects others'impressions of your organization, even if the focus of your organization has nothing to do with web technology.

  2. You may have valuable information on your web server. You may have sensitive or valuable information available in a restricted area that you may wish to keep unauthorized people from accessing. For example, you may have content or services available to paying members, which you would not want non-paying customers or non-members to access. Even files which are not part of your web server's document tree and are thus not available online to anyone, e.g., credit card numbers, could be compromised.

  3. Someone who has cracked your web server has easier access to the rest of your network. If you have no valuable information on your web server, you probably cannot say that about your entire network. If someone breaks into your web server, it becomes much easier for them to break into another system on your network, especially if your web server is inside your organization's firewall (which, for this reason, is generally a bad idea).

  4. You sacrifice potential income when your system is down. If your organization generates revenue directly from your website, you certainly lose income when your system is unavailable. However, even if you do not fall into this group, you likely offer marketing literature or contact information online. Potential customers who are unable to access this information may look elsewhere when making their decision.

  5. You waste time and resources fixing problems. You must perform many tasks when your systems are compromised. First you must determine the extent of the damage. Then you probably need to restore from backups. You must also determine what went wrong. If a cracker gained access to your web server, then you must determine how the cracker managed this in order to prevent future break ins. If a CGI script damaged files, then you must locate and fix the bug to prevent future problems.

  6. You expose yourself to liability. If you develop CGI scripts for other companies, and one of those CGI scripts is responsible for a large security problem, then you may understandably be liable. However, even if it is your company for whom you're developing CGI scripts, you may be liable to other parties. For example, if someone cracks your web server, they could use it as a base to stage attacks on other companies. Likewise, if your company stores information others consider sensitive (e.g. your customers'credit card numbers), you may be liable to them if that information is leaked.

These are only some of the many reasons why web security is so important. You may be able to come up with other reasons yourself. So now that you recognize the importance of creating secure CGI scripts, you may be wondering what makes a CGI script secure. It can be summed up in one simple maxim: never trust any data coming from the user. This sounds quite simple, but in practice it's not. In the remainder of this chapter, we'll explore how to do this.

Handling User Input

Security problems arise when you make assumptions about your data: you assume that users will do what you expect, and they surprise you. Users are good at this, even when they're not trying. To write secure CGI scripts, you must also think creatively. Let's look at an example.

Calling External Applications

figlet is a fun application that allows us to create large, fancy ASCII art characters in many different sizes and styles. You can find examples of figlet output as part of people's signatures in email messages and news group posts.

You can execute figlet from the command-line in the following manner:

% figlet -f fonts/slant 'I Love CGI!'

And the output would be...

...We can write a CGI gateway to figlet that allows a user to enter some text, executes a command like the one shown above, captures the output, and returns it to the browser.

First, here is the HTML form:

Example 8-1: figlet.html

Now, here's the program:

Example 8-2: figlet_INSECURE.cgi

#!/usr/bin/perl -w
use strict;
use CGI;
use CGIBook::Error;
# Constant: path to figlet
my $FIGLET = '/usr/local/bin/figlet';
my $q      = new CGI;
my $string = $q->param( "string" );
unless ( $string ) {
    error( $q, "Please enter some text to display." );
local *PIPE;
## This code is INSECURE...
## Do NOT use this code on a live web server!!
open PIPE, "$FIGLET \"$string\" |" or
    die "Cannot open pipe to figlet: $!";
print $q->header( "text/plain" );
print while ;
close PIPE;

We first verify that the user entered a string and simply print an error if not. Then we open a pipe (notice the trailing "|"character) to the figlet command, passing it the string. By opening a pipe to another application, we can read from it as though it is a file. In this case, we can get at the figlet output by simply reading from the PIPE file handle.

We then print our content type, followed by the figlet output. Perl lets us do this on one line: the while loop reads a line from PIPE, stores it in $_, and calls print; when print is called without an argument, it will output the value stored in $_; the loop automatically terminates when all the data has been read from figlet.

Admittedly, our example is somewhat dull. figlet has many options for changing the font, etc., but we want to keep our example short and simple to be able to focus on the security issues. Many people assume that for scripts this simple, it's hard for something to go wrong with them. In fact, this CGI script allows a savvy user to execute any command on your system...

Meet the Author

Scott Guelich graduated from Oberlin College in 1993 with a philosophy degree and decided to "only take a few years off" before continuing with graduate school. Unable to find any listing for "Philosopher Wanted" in the classifieds, and having done some programming while growing up, he quickly found himself working with computers. He discovered the Internet the following year and Perl the year after that. Scott has been a web developer for the past few years and currently contracts in the San Francisco Bay Area. He enjoys taijiquan, mountain biking, wind surfing, skiing, and anything that gets him outside and closer to nature. Despite the hours he spends working online, Scott is actually a closet Luddite who doesn't own a television, hasn't bought a cell phone, and still intends to make it to graduate school . . . some day.

Shishir Gundavaram graduated from Boston University with a BS in Biomedical Engineering in May of 1995. For his undergraduate thesis, he developed a Windows application for the Motor Unit Lab of the NeuroMuscular Research Center that allowed researchers to acquire and analyze muscle force output from patients to indirectly observe the electrical activity of muscles. He was the sole author of CGI Programming on the World Wide Web, published by O'Reilly & Associates, Inc., in 1996.

Gunther Birznieks is currently the chief technology officer for eXtropia.com, best known for its open source web programming archives and online tutorials in a variety of subjects related to web programming (Perl, CGI, Java). Before this, Gunther did web programming and infrastructure for the Human Genome Project. Most recently, he was an associate director at Barclays Capital where he had been the global head of web engineering.

Customer Reviews

Average Review:

Post to your social network


Most Helpful Customer Reviews

See all customer reviews

CGI Programming with Perl 4 out of 5 based on 0 ratings. 4 reviews.
Anonymous More than 1 year ago
STORY: <br>Many years ago, the bubonic plague was revived in a small town in Wyoming. It mutated itself and eventually spread across the entire nation, and soon the entire world. Its victims would go in a zombie-like state for a week, killing everything in sight, until they becone too weak to move and eventually die. It soon destroyed all of human-kind, and cats stepped up as the leading species of Earth. For about 50 years, things were peaceful, until the virus revived itself again, this time infecting cats. There is a small group that is immune to the disease, and are trying to get to Iceland, the last area on Earth that the disease hasn't touched. Everywhere else is respectfully called "The Dark Side of the Moon." This is where you come in. You are one of the few cats that are immune to the disease, and now, you must begin your pilgrimage to Iceland, where you can live in peace. Life is not over yet, in fact, it has only begun... <br> <br>RULES: <br>No godmodding. Keep ypur roleplaying realistic. <br>Be respectful. <br>No se<_> x. Get a room. <br>At least try to be literate when roleplaying. <br> <br>RANKS: <br>Leader: The one who- obviously- leads their group of cats. <br>Sidekick: They always stick by the leader, and help them in decision-making and keeping things in order. <br>Hunters: They "hunt" down zombies and other harmful cats. They also contribute in feeding the group of cats, usually by gathering seeds and berries, and hunting prey. <br>Kits: Kittens who are too young to be Hunters. Kits become Hunters at 8 moons.
Anonymous More than 1 year ago
Hello said a strong tom. My name is war. I am a black tom with red battle marks. I will assist you in whatever u need. Hes took a step foreward and you could see his big mussles flex. I am very brave and stong
Guest More than 1 year ago
Another excellent book from O'Reilly. I picked this up as a supplemental text for a course in CGI Perl programming and found myself reading every chapter. I found it refreshing that the text explained why certain elements are important as well as giving specific examples as how to implement them with Perl. Chapters on templates, email, data persistence, and the CGI Perl Module are especially helpful to the novice CGI programmer. The text does, however, assume that the reader has some familiarity with Perl and some JavaScript.
Guest More than 1 year ago
I am new at CGI and hoped that this book would help be develop my skills. I have a basic understanding of Perl, JavaScript and others, but I found my self lost from the begging. The authors seem to know what they are talking about, but the assume too much for the novice web designer. However, I did pick a few things up and I am still a fan of the O¿Reilly line of books.