Lesson 7 -- Printer Friendly Version

INSTRUCTIONS:

IMPORTANT: This version of your lesson is for saving or printing only. All links and images have been disabled to decrease download time and help you avoid printer difficulties.


Chapter 1

Today, you're going to learn how to build a CGI program that uses form data to automatically generate a custom web page for your site visitor.

Before you start, you'll need to get in touch with your hosting service.

Note: If you don't yet have a hosting service that supports CGI, it's time to get one. As I mentioned in lesson 5, you can set up a free business account with Hypermart at http://www.hypermart.net, a free personal account with WebProvider.com at http://www.webprovider.com or you can pay for hosting with IServer, Tabnet, or any other company that offers UNIX hosting with support for Perl CGI programming. Once you have an account, go back to part 2 (chapters 13 and 14) of lesson 5 and follow the illustrated tutorial to set up your server for CGI.

Once you contact your host, you'll need to get the following information:

1. The path to Perl on your server
You should already have this information, as you entered it on the first line of the programs you uploaded in lesson 5, 6, and 7. The path statement helps your program find the Perl interpreter on your server.

[usually /usr/bin/perl or /usr/local/bin/perl]

If you use Hypermart, the path to Perl is:

/usr/local/bin/perl

If you use WebProvider.com, the path to Perl is:

/usr/local/bin/perl

Please remember that this path is case-sensitive. In other words, don't use uppercase letters if your host requires lowercase letters.

2. The path to the CGI directory on your server
This is the place on the server where your CGI programs will be stored.

If you use WS_FTP, you can determine the path to your CGI directory by logging onto the server and double-clicking the CGI directory. Then, maximize the WS_FTP program so that it completely fills your screen. Glance up at the top right corner of the WS_FTP window, just below the words 'Remote System' and you'll see the path to your CGI directory. On Hypermart, it might look something like this:

/data9/hypermart.net/username/cgi-bin/

If you use WebProvider.com, the path will look something like this:

/disk1/u/username/public_html/cgi/

(You'll want to substitute the first letter of your username for 'u,' your actual WebProvider.com username for 'username,' and your actual CGI directory for 'cgi' in the example above.

Please remember that this directory name is case-sensitive.

3. The URL of your CGI directory
This is the web address your site visitors will use to access the scripts you'll be creating. Although both the server path and the URL lead to the same place (your CGI directory), a URL is not the same as the server path. The server path provides directions a script running on your server can use to find the CGI directory on the same machine. The URL is intended to lead a browser running on another machine to the CGI directory on your server.

By now, you already should know the URL for your CGI directory. You entered this URL into your browser each time you ran the scripts you created in lessons 5 and 6.

The easiest way to distinguish a URL from a server path is to look for the letters 'http.' If those four letters are present, you're looking at a URL. If they are absent, you're looking at a server path.

If you use Hypermart, your URL will look something like this:

http://username.hypermart.net/cgi-bin/

If you use WebProvider.com, your URL will look something like this:

http://username.webprovider.com/cgi/

Be sure to substitute your actual Hypermart or WebProvider user name for username and the name of your WebProvider.com CGI directory for 'cgi' in the example above. Also, please remember that your URL is case-sensitive.

Before you begin, I would also recommend that you go to the Supplementary Material page at the end of this lesson. You'll find a working demo of the form and program we're about to create. You'll also be able to download a very useful library of Perl subroutines (short but useful Perl scripts) named cgi-lib.pl. You'll learn lots more about this file later.

Before you begin, I would also recommend that you go to the Supplementary Material page at the end of this lesson. You'll find a working demo of the form and program we're about to create. You'll also be able to download a very useful library of Perl subroutines (short but useful Perl scripts) named cgi-lib.pl. You'll learn lots more about this file later.

Chapter 2

Let's begin by creating the HTML form our visitors will use to submit data for our script to work with. For variety's sake, let's build a form containing a text box, a hidden field, a set of radio buttons, a checkbox, a drop-down list, and a submit button.

All of the input devices we'll need to create must be surrounded by <form> and </form> tags.

The initial <form> tag should hold the URL leading to the CGI program you'll be creating later in this lesson. Later in this lesson, we'll build and save a program named 'showform.cgi.' If the URL of your CGI directory were http://username.hypermart.net/cgi-bin, then the <form> tag that would call such a program might look something like this:

<form action="http://username.hypermart.net/cgi-bin/showform.cgi"
method="post">
Remember, the URL of your CGI program will not be identical to the example above. The URL should contain your domain name, the name of your CGI directory, and the name of the CGI script that you want to run when this form is submitted. The URL should be roughly the same as those you used to run the scripts you developed in lessons 5 and 6. The only difference will be the name of the script you want to run. If you aren't sure of your URL, check with your hosting service.

Let's roll up our sleeves and start writing the HTML code for our form. To do so, please start Notepad or a similar text editor and type the following HTML code. If the directory where you store your CGI programs is not named 'cgi-bin', please remember to use the name of your CGI directory instead of 'cgi-bin' in the <form> tag below.

Notice how I used all lowercase letters for the field names. Field names are case-sensitive. By consistently using all lowercase letters, I don't have to worry about case sensitivity. All I have to do is remember to always type my field names using lowercase letters and I won't be forced to deal with introducing case-related errors when I write my program later.

For more background information on HTML forms, please refer to lesson 5.

<html>
<body bgcolor="white" text="black">
<P>Please fill out our form:</P>

<form action="http://username.hypermart.net/cgi-bin/showform.cgi"
method="post">

<input type="hidden" name="lesson" value="7">

<P>First Name:<BR>
<input type="text" size="40" name="firstname">
</P>

<P>Favorite Color:<BR>
<select name="color">
<option value="blue">blue
<option value="black">black
<option value="cyan">cyan
<option value="green">green
<option value="grey">grey
<option value="orange">orange
<option value="purple">purple
<option value="red">red
<option value="white">white
<option value="yellow">yellow
</select>
</P>

<P>Favorite Beverage:<BR>
<input type="radio" name="beverage" value="milk">
Milk

<input type="radio" name="beverage" value="water">
Water

<input type="radio" name="beverage" value="coffee">
Coffee

<input type="radio" name="beverage" value="tea">
Tea

<input type="radio" name="beverage" value="soda">
Soda

<input type="radio" name="beverage" value="juice">
Juice
</P>

<P>
<input type="checkbox" name="bike" value="yes">
Check this box if you have a bicycle.
</P>


<P><input type="submit" value="Submit Data">
</P>
</form>
</body>   
</html>
When you finish typing your form, click the 'File' menu and choose 'Save As' to save your form. Choose a drive and directory and name the form 'form.htm' or, if your operating system supports four-letter extensions, call it 'form.html' instead.

Then, use your FTP program to upload this HTML file to your hosting service. Place it in the same directory as your home page and the rest of your HTML files. Because this file is not a Perl script, it will not be necessary for you to upload the file to your CGI directory nor will it be necessary for you to use chmod to set permissions for this particular file. After you upload the file to your HTML directory, you're ready to continue.

Chapter 3

Whenever someone fills out your form, the form data is going to be posted to your CGI program in a message file named stdin (see lesson 1 for more info on stdin and the post method).

Before your program can generate a custom page based on the data users enter on your form, it will need to collect the incoming form data and store it in an associative array (we talked about associative arrays in lesson 6).

In this associative array, the names of your text boxes, radio buttons, and other input devices will need to be associated with the values your visitor entered into each of those input devices.

For example, if a user entered the name 'Bob' in the text box named 'firstname,' you would want to associate the value your user entered (Bob) with the name of the text box containing that value (firstname).

Although you could write a series of Perl commands to carry out this activity yourself, there is absolutely no need for you to reinvent the wheel. A kind young man named Steven Brenner has already developed a library of procedures commonly carried out by perl programmers. Steven refers to these oft-used perl procedures as 'subroutines.'

The product of his labors, a file named 'cgi-lib.pl,' has been placed in the public domain. The cgi-lib.pl file is filled with subroutines designed to save you time and effort.

In the cgi-lib.pl file, each of the subroutines is identified with a line that starts with the word 'sub' followed by a space and the name of the subroutine.

The perl commands that make up the subroutine follow on subsequent lines. The commands are surrounded by {curly brackets}.

An example

Here is an example of a very short subroutine found in the cgi-lib.pl file. This subroutine can be used to print the Content-type line you first learned about in lesson 2.

sub PrintHeader {return "Content-type: text/html\n\n";}
Thanks to Steven, you can just invoke this subroutine whenever you need to set the content-type in your CGI program. All you have to do to invoke this subroutine is type the following command:

&PrintHeader;  
The '&' tells the perl interpreter to look for a subroutine named 'PrintHeader' and to process the instructions contained within that subroutine. When we call this subroutine, it will return (send) the words 'Content-type: text/html\n\n' to our script.

There's just one hitch. If you'll recall from your previous lessons, we need to precede the 'Content-type' statement the subroutine will be returning with a 'print' command in order for it to work properly. In other words, whenever you need to set the content type, just type:

print &PrintHeader;   
instead of

print "Content-type: text/html\n\n"; Ask yourself: which of the two commands above is easier to type? Which is easier to remember? Which would be less likely to contain a typo? I am sure you will agree that the '&PrintHeader;' command is the answer to all three questions.

Thanks to Steven's subroutines, we can program faster, more efficiently, and with fewer errors!

Inside the cgi-lib.pl file, you will find another very useful subroutine named 'ReadParse.' Whenever you want your CGI program to process incoming form data, all you have to do is call up the ReadParse subroutine! This subroutine will store the form data in an associative array named %in.

ReadParse would have no difficulty with the form you created earlier in this lesson. If someone were to type 'Marybeth' in the text box named 'firstname' and this same person selected 'blue' from the drop-down list named 'color', ReadParse would create the following associative array in short order:

%in=('firstname','Marybeth','color','blue');

As you learned in lesson 6, you could extract each of the values from an array like this with a simple foreach loop. You could also extract individual values from the array--such as the visitor's first name--by asking for the value of a variable named $in{'firstname'}. Likewise, your visitor's favorite color would be stored in a variable named $in{'color'}.

How to Implement cgi-lib.pl

In order for the cgi-lib.pl file to work its magic, you need to do four things:

1. Download cgi-lib.pl

Go to the Supplementary Material page and click the link that says 'Download cgi-lib.pl.'

When the cgi-lib.pl file appears in your browser, click your browser's 'Edit' menu and choose 'Select All.'

Then, click the 'Edit' menu again and choose 'Copy'.

Now, start a new document in your text editor. Click the 'Edit' menu at the top of your text editor and choose 'Paste'. This should place a copy of the cgi-lib.pl file in your text editor.

Make sure the file you are looking at is identical to the file on the website. If the file was truncated or contains little black squares or other non-text characters, it won't work.

If you're satisfied that the file has been copied intact, click your text editor's 'File' menu and choose 'Save As' to save the file in the same folder on your hard disk as the form.html file you created earlier. Make sure and name the file "cgi-lib.pl" (if you use Notepad, surround the name with quotes. If you use another text editor, the quotes should not be necessary). Do not allow your text editor to throw any additional extensions on the end of that name.

2. Add a 'require' statement to your Perl scripts

You don't need to do this just yet. However, each time you write a Perl script that requires the services of cgi-lib.pl, you must remember to add the following line to the beginning of the CGI program (just after the path to Perl):

require "cgi-lib.pl";  
This statement tells the program to place the subroutines contained within the cgi-lib.pl file at your disposal. Remember, Perl is case- sensitive. You will want to type the line above entirely in lower case. Notice also that the only space in the entire line is the one that follows the word 'require.'

IMPORTANT: This is not a problem with Hypermart (or most other hosting services), but if your server ever gives you an error message that indicates it "Can't locate cgi-lib.pl" when you try to run a script that uses the cgi-lib.pl subroutines, then you will need to provide the path to your CGI directory (and the cgi-lib file contained therein) in your require statement. For example, if you're a Webprovider.com user, you may get such a message. To help your server locate the cgi-lib.pl file, you will need to modify your require statement so that it includes the path to your CGI directory:

require "/disk1/u/username/public_html/cgi/cgi-lib.pl";
Where 'username' is your username, 'u' is the first letter of your username, and 'cgi' is the name of your CGI directory. If you're not sure, check with your host for the correct path to your CGI directory.

3. Call the 'ReadParse' subroutine

Again, you don't need to do this right now. But if you want to read the incoming form data into an array named %in, you must add the following command to the beginning of your CGI program, just after the 'require' statement:

&ReadParse;
This command tells the program to run the cgi-lib.pl subroutine named 'ReadParse.' Again, remember that Perl is case-sensitive. ReadParse is the name Steven chose for the subroutine that converts incoming form data into an associative array. We must respect his naming conventions. When you type ReadParse, be sure to capitalize the 'R' and the 'P' and type the rest of the name in lower case.

The '&' at the beginning of the command tells the Perl interpreter that ReadParse is a subroutine. The Perl interpreter will go racing through your program, and then through the cgi-lib.pl file, searching for a subroutine named 'ReadParse.' When the interpreter finds the subroutine, it will carry out all of the instructions contained therein.

4. Upload the cgi-lib.pl file to your cgi-bin directory.

You don't need to upload anything at this point in time, but from now on, please remember that if you upload a CGI program that requires cgi-lib.pl, you must also remember to upload the cgi-lib.pl file (in ASCII mode) as well. The cgi-lib.pl file must be saved to the same directory and must be assigned the same permissions as your CGI program.

Chapter 4

Now that we have the ground rules out of the way, let us now create a program that will intercept the incoming form.html form data and display it on a web page.

WARNING: Please be very, very, very careful when typing this program. If you leave out just one semicolon or quote mark or slash or spell one word correctly, I can guarantee that your program won't run. Tracking down a missing or extraneous character can literally take hours. Work slowly and carefully, and you should have no trouble!

Please start a text editor, such as Windows Notepad or Apple's MacText or SimpleText. It is important that your CGI program be saved as a text file or it flat-out will not work.

As you learned in lesson 2, your program will need to start with the path to the perl interpreter. Although mine is /usr/local/bin/perl, yours may be different. Look at the beginning of the programs you succesfully tested in lessons 5 and 6 if you don't remember your correct path.

Make sure that the path to Perl appears on the very first line of your program. The path cannot be preceded by a blank line, a space, or anything else:

#!/usr/local/bin/perl
Next, please type the two lines required to run the 'ReadParse' subroutine in the cgi-lib.pl file (remember, if you use Webprovider.com, you might be required to type the path to your CGI directory in the require statement. Check the section dealing with the 'require' statement in chapter 3 of this lesson for more instructions):

require "cgi-lib.pl"; 
&ReadParse;
Before we send our visitor any HTML code, we will need to set the content type. Let's take advantage of the 'PrintHeader' subroutine we talked about earlier to do this (set the content type). Calling the subroutine will be a lot easier than typing all that print "Content-type: text/html\n\n"; nonsense!

print &PrintHeader;  
Now, let's create a web page for the visitor to see after they submit our form. If we don't send the visitor some sort of confirmation over the web, chances are good that they will think our form isn't working right. Many will click the 'submit' button over and over and over again! By sending a simple confirmation message, the visitor gets a bit of psychological reinforcement and leaves our form knowing all is well. We'll need to begin with <HTML> and <body> tags:

print "<HTML><BODY>";
Next, let's set up a foreach loop that will extract each of the values from the associative array named %in. Remember, this array was created by the cgi-lib.pl subroutine named ReadParse that we called just a few lines earlier. You learned this little trick at the end of lesson 6.

foreach $i (keys %in)
{
 print "<P>$i = $in{$i}</P>";
}
The loop above will cause our script to create a new paragraph for each item in the associative array. It will print the key (the name of the input device), an equal sign, and the value our user entered into the input device referenced by the key.

Finally, let's close the BODY and HTML tags:

print "</BODY></HTML>";
It's always a good idea to place a comment at the end of your code that tells you (and others who might edit your code) where the end of the file lies. Press the ENTER key a couple of times and add the following:
#End of program
That's it! Click the 'File' menu and choose 'Save As' to save your work. Place the file on the same drive and in the same folder as your cgi-lib.pl and form.html files. Name this file "showform.cgi"

Make sure the name of this file exactly matches the file name referenced in the ACTION parameter of your form.html file's FORM tag. There must not be any differences in the spelling or the letter case.

Here's the complete code:

#!/usr/local/bin/perl
require "cgi-lib.pl";
&ReadParse;
print &PrintHeader;
print "<HTML><BODY>";
foreach $i (keys %in)
{
 print "<P>$i = $in{$i}</P>";
}
print "</BODY></HTML>";

#end of program

Chapter 5

It is now time to upload the cgi-lib.pl and showform.cgi files to your server.

First, make sure you have already uploaded the form.htm or form.html file to your server. Because this form is nothing more than a simple web page, remember to place this file in the same directory as your home page and all your other web pages. As I mentioned before, it will not be necessary for you to set the file permissions for this file.

Secondly, instruct your FTP program to go to the directory you have set aside for CGI programs. This directory is usually called cgi-bin. If you're using WS-FTP 95, all you have to do to enter the directory is double-click.

Next, set your FTP program to transmit in ASCII (text) mode and send the showform.cgi file to the special CGI directory. Make sure the file is named showform.cgi and not Showform.cgi or SHOWFORM.CGI or showform.cgi.txt or shoform.cgi or some other variation. If the name is not exactly right, click once on the file and then click your FTP program's 'Rename' button to correct the name of the file before you upload!

Once the showform.cgi file has been uploaded, verify that your FTP program is set to transmit in ASCII mode and upload the cgi-lib.pl file to the same directory as your showform.cgi file. Again, verify that the name of the file is cgi-lib.pl and not Cgi-Lib.pl or CGI-LIB.PL or cgi_lib.pl or cgi-lib.pl.txt or some other variation. If the name isn't right, rename the file before you upload.

Once your two files reach the special CGI directory on your server, point your mouse at the showform.cgi file on your server (files on your server are listed on the right side of the WS_FTP window), click the left mouse button once to select the file, and then click the right mouse button. If you're using WS_FTP, a menu should pop up. Somewhere on this menu, you will find the UNIX chmod command. Click your left mouse button on chmod.

After clicking the chmod command, you must indicate who should have access to your files and what type of access they should have.

As you learned in lesson 5, there are essentially three types of individuals who can access your file. You are the owner of the file, and you should give yourself the right to read (open), write (modify), and execute (run) the program. The rest of the world should only be allowed to open and run your program. They should not be allowed to modify the program in any way, because that could represent a security risk.

The procedure for setting file permissions varies from FTP program to FTP program. If you use WS_FTP, all you have to do is click your mouse in some checkboxes next to the words 'read' 'write' and 'execute.' Other programs may require you to type in the letter 'r' for 'read,' 'w' for 'write,' and 'x' for execute. Set your file permissions as follows:

Owner - read, write, and execute privileges.

Group - read and execute privileges.

Other/World - read and execute privileges only.

If your FTP program requires you to set permissions by entering a three digit number (as described in the last two chapters of lesson 5), you'll want to set the permission to 755. Once the file permissions for showform.cgi have been set, click your left mouse button on the cgi-lib.pl file on your server to select the file. Then, click the right mouse button to bring up the menu. Select the chmod command and give the cgi-lib.pl file the exact same permissions you gave showform.cgi.

When you finish uploading and setting file permissions for both the showform.cgi AND the cgi-lib.pl file, you're ready to test your program!

Stay logged onto the Internet.

Next, start your web browser and type in the URL of your form. For example, if your form file is named form.htm and it is located at http://www.yourcompany.com, you would want to type the following in the little URL box at the top of your browser:

http://www.yourcompany.com/form.htm

If you're a Hypermart member, you'd type something like this (being careful to substitute your real user name for username:

http://username.hypermart.net/form.htm

The form you created in chapter 2 of this lesson should appear on your screen. If it does not appear, fire up your FTP program and try uploading the HTML file again. Check the name of the file carefully--make sure it is spelled correctly and that you used lower case letters. Also, make sure that you are uploading this file into your HTML directory and not into your CGI directory. The two types of files are usually segregated from one another.

Once the form appears, supply a value for each input device and click the 'Submit' button.

After a brief pause, you will see a message similar to one of the following:

Message One


beverage = juice

firstname = Joe

bike = yes

lesson = 7

color = grey

EXPLANATION: If you receive a message similar to the one above, your program worked perfectly. No further modification will be necessary.

IMPORTANT: If you don't see a value for the input device named bike, don't panic. The associative array will only store a value for bike if you check the box. If you failed to check the box, bike will not have a value and will not be added to the associative array by the ReadParse subroutine. However, if the value of beverage or firstname or lesson or color is not showing up, then check each of the input devices in your form file for errors. You forgot to give the input device a name and/or value parameter. If you make changes to the form, please remember to upload the revised file to the HTML directory and not the CGI directory. Each time you bring a revised form up on your browser, hold down your SHIFT key and click the browser's 'Reload' or 'Refresh' button to clear the old form from your cache or your changes won't hold.

Message Two


403 Forbidden

Your client does not have permission to get URL cgi-bin/showform.cgi from this server.


EXPLANATION: If you see a 403 message like the one above, it means that you have not set file permissions properly. The world needs to be able to read and execute your cgi file.

SOLUTION: Use your FTP program's chmod command to change the file permissions. If you use WS_FTP, you can right- click on the file after you've uploaded it to your CGI directory. Give the owner read, write and execute privileges. Give the group read and execute privileges. Give the world (also known as other) read and execute privileges.

If you have Telnet and know how to use it, you could Telnet to your server and enter the cgi-bin subdirectory. Then, issue the following UNIX command: chmod 755 showform.cgi

Message Three

500 Server Error

The server encountered an internal error or misconfiguration and was unable to complete your request.


EXPLANATION: This is the most common error. It is always caused by a typo in your program or by forgetting to upload a needed file (such as the cgi-lib.pl file). If you see this error, then:

SOLUTION: Look for and correct spelling errors. Make sure you didn't leave out a quote mark, semicolon, parenthesis, or bracket. I find that a missing semicolon at the end of a line or an extra quote mark or an incorrect path to Perl is almost always to blame for this error. Sometimes a second set of eyes can help you spot your typo. Have a friend, coworker or relative look over your code and compare it to mine to find the error. If that doesn't solve your problem, delete the program and cgi-lib.pl files from your server, re-upload them in ASCII mode, and set the file permissions again. If that doesn't work, compare your cgi-lib.pl file to mine and make sure they are identical.

If you can't figure out where the typo is, then ask your host to let you see the entries in the error.log file on your server (Hypermart does this for you automatically every time you have an error). The error.log file will display a message that usually tells you exactly which line of your program contains the typo or which file doesn't have its permissions set correctly.

Message Four


404 Not Found

The requested URL cgi-bin/showform.cgi was not found on this server.


EXPLANATION: The server cannot find the file specified in the ACTION parameter of the <form> tag in your form.html file.

SOLUTION: Make sure that you have uploaded the showform.cgi file to the directory specified in your form.html file's <form> tag. If the showform.cgi file is in the correct directory, then your <form> tag contains an error. Make sure you spelled the name of the showform.cgi file correctly, using all lower case (file names are case-sensitive). If the file name is spelled correctly and the case is right, then your <form> tag is probably not pointing to the right directory. Ask your hosting service what your <form> tag needs to say so that your form can call up the showform.cgi program.

Message Five

Well, this really isn't a message, but sometimes your CGI file will just print out on the screen. Instead of running, the program will just display your source code.

EXPLANATION: The server isn't executing your file.

SOLUTION: The server either can't find the Perl interpreter or doesn't recognize the file extension you used. Make sure that your showform.cgi file name ends with a .cgi extension and not .txt or some other extension. If it does, look at the first line of your CGI file. Does it have a number sign (#) followed immediately by an exclamation point (!) and the correct path to perl? Check with your hosting service. Ask them what extension you should use on your CGI programs and what the very first line of your CGI program should say.

Chapter 6

The showform.cgi script you just finished working with is a great generic script that will take data from any form and display the names and values of the form fields on your screen each time the form is submitted. I always use the showform.cgi script to test every form I create to verify that the input devices are functioning as planned. Whenever I create a new form, I point the ACTION parameter of the FORM tag to the showform.cgi script temporarily. I upload the form to my server, call it up in my browser, fill in the fields and submit. The showform.cgi program should then show me the names of all of the input devices on my form and the values that I entered into those input devices. If anything is missing, I know that I've made an error on my form and take corrective action.

Exercise:

Try creating a brand new form with text boxes, hidden fields, radio buttons, checkboxes, a drop-down list, and a textarea. Give the new form the same FORM tag that you used with the form.html file (so that the showform.cgi file processes the form data immediately after it is submitted). Save the file as exercise.htm or exercise.html and upload the form to your HTML directory. Load the new exercise.html form in your browser, fill it out, and submit it. The showform.cgi script should have no difficulties displaying the names of the input devices on your new form along with the values you entered into these input devices.

Unfortunately, the foreach loop employed by the showform.cgi doesn't give us much control over how the output is formatted. We can't even control the order in which the names and values are displayed. Even though the firstname field is the first input device on our form, the foreach loop reorders the name and value pairs in the associative array and display firstname only after it has displayed another value.

If you want more control over what your visitor sees after submitting the form, you'll probably need to avoid using the foreach loop and extract each value from the associative array named %in individually.

Our form contains five input devices with the following names:

  1. A hidden field named lesson;
  2. A text box named firstname;
  3. A drop-down list named color;
  4. A checkbox named bike; and
  5. A set of radio buttons named beverage.
To extract the value contained within the hidden field named lesson from the associative array named %in, all you have to do is type the following:

$in{'lesson'}
Likewise, you can extract the value of the text box named firstname by typing the following:

$in{'firstname'}
And you can figure out which radio button the user selected by typing:

$in{'beverage'}
The value of the checkbox named bike can be discerned by typing:

$in{'bike'}
Exercise:
How could you determine the value our user selected from the drop-down list named color?

Solution: (no peeking until you've come up with your own answer)

$in{'color'}
That said, let's write a little script that allows us to output the form data in a more pleasing fashion.

This script, like all the others you've written, should begin with the path to Perl (yours may be different):

#!/usr/local/bin/perl
Next, please type the two lines required to run the 'ReadParse' subroutine in the cgi-lib.pl file (if you use Webprovider.com, you may be required to supply the full server path to the cgi-lib.pl file here):

require "cgi-lib.pl"; 
&ReadParse;
Before we send our visitor any HTML code, we will need to set the content type. Once again, let's take advantage of the 'PrintHeader' subroutine:

print &PrintHeader;  
Let's begin our web page with the requisite <HTML> and <body> tags:

print "<HTML><BODY>";
Now, instead of using a foreach loop to extract the values from the associative array in hit-or-miss fashion, let's extract the values in a more controlled fashion:

print "<p><b>First Name:</b><br>";
print "$in{'firstname'}</p>";
print "<p><b>Favorite Color:</b><br>";
print "$in{'color'}</p>";
print "<p><b>Favorite Beverage:</b><br>";
print "$in{'beverage'}</p>";
print "<p><b>Lesson Number:</b><br>";
print "$in{'lesson'}</p>";
We won't know whether or not our user has selected or deselected the checkbox named bike, so let's perform a little test. If the checkbox has been selected, we'll print one sentence. If not, we'll print another:

if ($in{'bike'} eq "yes")
{
 print "<p><b>Has a bike</b></p>";
}
else
{
 print "<p><b>Does not have a bike</b></p>";
}
Finally, let's close the BODY and HTML tags:

print "</BODY></HTML>";
It's always a good idea to place a comment at the end of your code that tells you (and others who might edit your code) where the end of the file lies. Press the ENTER key a couple of times and add the following:
#End of program
That's it! Click the 'File' menu and choose 'Save As' to save your work. Place the file on the same drive and in the same folder as your cgi-lib.pl and form.html files. Name this file "newform.cgi"

Here's the complete code:

#!/usr/local/bin/perl

require "cgi-lib.pl"; 
&ReadParse;

print &PrintHeader;  

print "<HTML><BODY>";

print "<p><b>First Name:</b><br>";
print "$in{'firstname'}</p>";
print "<p><b>Favorite Color:</b><br>";
print "$in{'color'}</p>";
print "<p><b>Favorite Beverage:</b><br>";
print "$in{'beverage'}</p>";
print "<p><b>Lesson Number:</b><br>";
print "$in{'lesson'}</p>";

if ($in{'bike'} eq "yes")
{
 print "<p><b>Has a bike</b></p>";
}
else
{
 print "<p><b>Does not have a bike</b></p>";
}

print "</BODY></HTML>";

#End of program
Now, open the form.html file in your text editor and change the file name referenced in the ACTION parameter of the FORM tag so that it points to 'newform.cgi' instead of 'showform.cgi'. Save the modified HTML file as newform.htm or newform.html.

Next, use your FTP program to upload the newform.html file to the HTML directory on your server. It will not be necessary for you to set permissions on this file.

When you finish, go to the CGI directory on your server, set your FTP program to transmit in ASCII mode, and upload the newform.cgi file to the server. Make sure that the file lands in the same directory as the cgi-lib.pl file, because the program you have just written will require the services of a couple cgi-lib.pl subroutines.

Use the chmod command to set the permissions on the newform.cgi file to rwx r-x r-x (the same permissions you gave the showform.cgi file and the cgi-lib.pl file in the previous chapter).

When the permissions are set, start your browser and load your newform.html file. Fill out the form and click the submit button. You should receive a page that looks something like this:

First Name:
Susan

Favorite Color:
red

Favorite Beverage:
milk

Lesson Number:
7

Does not have a bike
If you receive an error message instead, there is either a typo in your CGI script (look for a missing quote mark or semicolon) or there is an error in the ACTION parameter of the FORM tag in your newform.html file. Check the end of the preceding chapter for troubleshooting tips.

Exercise:
Modify the newform.cgi file so that it produces a web page containing a sentence like the following (assuming the user submits 'Susan' as the firstname and 'red' as the color):

Thanks, Susan. I now know that your favorite color is red.
If the user submits a firstname of 'Frank' and a color of 'blue,' your program should be smart enough to produce a sentence that looks like this:
Thanks, Frank. I now know that your favorite color is blue.
Solution: (try not to peek):
#!/usr/local/bin/perl

require "cgi-lib.pl"; 
&ReadParse;

print &PrintHeader;  

print "<HTML><BODY>";

print "<p><Thanks, $in{'firstname'}.";
print "I now know that your favorite color is $in{'color'}</p>";

print "</BODY></HTML>";

#End of program

Chapter 7

-Quiz 7-

No quiz this time.

IMPORTANT: This version of your lesson is for saving or printing only. All links and images have been disabled to decrease download time and help you avoid printer difficulties. Do NOT attempt to click any of the links on this page.

Copyright 1999 by ed2go.com. All rights reserved.
No reproduction or redistribution without written permission.

1