Your First CGI Program
After all the fanfare, warnings, checklists, and runaround, you're ready to type in your first CGI program. It is shown in Listing 21.1.
Type and save this program as hello. If, in the checklist, you are required to use a certain extension for CGI programs—as noted in the "Extension to be used for CGI programs" item—use that extension. Thus, if you're required to name your CGI programs with a .cgi extension, save this script as hello.cgi. If you're required to use .pl, save this script as hello.pl.
You did fill out the checklist, didn't you?
Listing 21.1. Your First CGI Program
1: #!/usr/bin/perl -w
2: use CGI qw(:standard);
3: use strict;
5: print header;
6: print "<b>Hello, World!</b>";
This line is the standard #! line. You must substitute the path from the checklist item "Location of Perl on the web server" for this script to work. The -w, of course, enables warnings.
The CGI module is included in the program. The qw(:standard) causes the standard set of functions from the CGI module to be imported into your program.
use strict enforces good coding practices; this is no different for CGI programs.
The header function is imported from the CGI module. It prints a standard header that the server (and the client) must see to process the output of the CGI program.
After the header is printed, any output will appear normally to the browser. In this case, when the CGI is run, the browser will display the words Hello, World.
Well, not quite. You still have to install this CGI program and test it. You've won only half the battle.
Installing the CGI Program on the Server
How you install your CGI program depends heavily on what kind of server you have, whether you have local access to it, whether it's a server that you can only FTP files to, and so on. The following sections describe how to install for the different scenarios.
Local Access to a File System on a Unix Web Server
Use these instructions if you're able to telnet, rlogin, or otherwise log in to the Unix web server:
Put the CGI program hello.cgi (or hello.pl) onto the Unix server, perhaps with FTP.
You may have actually written it on the server with vi. That's fine, too.
Move the CGI program into the correct directory by using the mv or cp command.
You should have found the correct directory in the checklist under "Location of CGI program directory."
Under Unix, you need to make the program executable. Do so by issuing the following command:
chmod 755 hello.cgi
Use hello.pl instead if it is the program's name. This command makes the file writable by the owner and readable and executable by everyone else (this is correct for a CGI program).
FTP-Only Access to a Unix Web Server
Use these instructions if you have FTP-only access:
Use your FTP client to put the hello.cgi (or hello.pl) program into the CGI program directory. You should have found the correct directory in the checklist under "Locati