Building a CGI Script, From Form to Response

The best way to learn how to code CGI is to go ahead and do it, so let's do it. In this section we'll create a really simple CGI script—the equivalent of Hello, World—using a basic HTML form, Perl for the CGI script, and the CGI.pm module to help put it all together. I'll give you the HTML form to work from, but we'll build up the script itself line by line.

The Form

Listing 16.1 shows the HTML code for a simple HTML form that asks you for your name. Figure 16.2 shows what this form looks like in a Web browser.

Figure 16.2. Hello!


Listing 16.1. The name.html File
1:  <html>
2:  <head>
3:  <title>Tell Me Your Name</title>
4:  </head>
5:  <body>
6:  <form action="/cgi-bin/name.pl">
7:  <p>Enter your Name: <input name="name" /></p>
8:  <p><input type="submit" value="Submit me!"></p>
9:  </form>
10: </body>
11: </html>

There are two important parts to note about this bit of HTML:

  • In Line 6, the action attribute points to the CGI script that will process this form when it's submitted to the server. Here, that script is called name.pl, and it's stored in the server's cgi-bin directory (the usual place for CGI scripts to be stored, although it might be different for your server, or you might need permission to put your scripts there). You'll need to substitute the path to your version of the script when you write it in the next section.

    Note

    Some Web servers might also require you to rename your scripts with a .cgi extension for those scripts to be recognized as CGI scripts. This differs from server to server, so check your documentation.


  • Line 7 defines a text field form element (in the <input> tag). Note that the name attribute gives this element a name. This will also be important when you build the CGI script for this form.

Creating the Script

Now let's create a Perl script to process the data we get back from that CGI script. Although writing a CGI script in Perl is similar in many ways to writing an ordinary command-line Perl script, there are several important differences relating to the fact that your script is called by the Web server, not by you. You won't get any command-line options or filename arguments. All the data you get into the script will come from the Web server (or you'll read it in yourself from files on the disk). The output you write will have to be in a specific format—usually HTML.

Fortunately, the CGI.pm module, written by Lincoln Stein and available as part of the standard Perl installation, is there to make CGI scripting easier and to cover up a lot of the oddities.

Let's start with the top couple of lines of our CGI script:

#!/usr/local/bin/perl -w
use strict;
use CGI qw(:standard);

The shebang line and use strict you already know, and the third use CGI line shouldn't be much of a surprise either. The :standard tag, as you learned on Day 13, “Scope Models and Importing Code,” imports a subset of the CGI module, rather than importing the whole thing. In the case of CGI.pm, the :standard tag will probably be the one you use most often. (It exports most of the commonly used subroutines in the module into the namespace of your script.)

Most CGI scripts have two main parts: the initial part reads and processes any data you got from the form or from the Web browser, and the second outputs a response, usually in HTML form. In this example, because there isn't any real processing to do, we can skip directly to the output part.

The first thing you need to output is a special header to the Web server indicating the kind of file you're sending back. If you send back an HTML file, the type is text/html. If you send back a plain text file, it's text/plain. Send back an image, and it's image/gif. These file types are all standardized as part of the MIME specification, and if you get into serious CGI scripting you'll need to learn at least some of these. The most common type, however, is text/html. CGI.pm provides a basic subroutine, print_header(), for printing out the appropriate header for that type:

print header();

After the header, all the output you print will be in HTML format. You can either print raw HTML tags or use CGI.pm's Perl subroutines for generating HTML, or you can use a combination of both. Because I know HTML fairly well, I like to use the CGI.pm subroutines where it will save me some typing, and regular print statements for everything else. Here's the remainder of our simple CGI script:

print start_html('Hello!'),
print "<h1>Hello, ", param('name'), "!</h1>
";
print end_html;

The first line calls CGI.pm's start_html() subroutine, which prints the top part of an HTML file (the <html>,<head>,<title>, and <body> tags). The string argument to start_html() is the title of the page. There are also other arguments you can give this subroutine to set the background color, keywords, and other features of the header (more about that in the next section).

The second line is a regular print statement, which prints an HTML heading (<h1> tag) to say hello. In between the opening and closing tags, however, is the interesting part. The param() subroutine, part of CGI.pm, is how you get to the information that your user entered into the form. You use param() with the name of the form element (from the name attribute of the element's HTML tag), and it returns the value the user entered for that element. By calling param('name') here, we get the string the user entered into the one text field on our form, and we can use that value to generate the response.

The third line is another CGI.pm subroutine that simply prints out the closing bits of HTML (</body> and </html>), finishing up the response. Here's the complete script, all put together:

#!/usr/local/bin/perl -w
use strict;
use CGI qw(:standard);

print header;
print start_html('Hello!'),
print "<h1>Hello, ", param('name'), "!</h1>
";
print end_html;

You might have noticed that we're not doing anything special as far as output is concerned; we're just using simple print statements. And yet, the output doesn't go to the screen; it goes back to the browser. A CGI script is a prime example of how standard input and output don't necessarily have to be the keyboard or the screen. CGI scripts do read their input from the standard input, and output to the standard output. Except in this case the standard input and output is the Web server. You don't have to do anything special to deal with that server; the standard ways work just fine.

So what is the output? If the user entered “Fred” into the form, the output of the CGI script will look like this, with the header and the HTML data in place:

Content-Type: text/html; charset=ISO-8859-1

<?xml version="1.0" encoding="utf-8"?>
<!DOCTYPE html
   PUBLIC "-//W3C//DTD XHTML Basic 1.0//EN"
   "http://www.w3.org/TR/xhtml-basic/xhtml-basic10.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" lang="en-US"><head><title>Hello!</title>
</head><body><h1>Hello, Fred!</h1>
</body></html>

That data will get passed over the standard output to the Web server, which in turn will pass it back to the Web browser that Fred is running.

..................Content has been hidden....................

You can't read the all page of ebook, please click here login for view all page.
Reset