By now, you've seen lots of Web pages and probably have created a few of your own. Web pages are really neat. They can be full of wonderful graphics and text, but if that's all they have on them, they're not much more than an electronic version of a paper brochure. Up to this point in the book, you have seen some of the simpler ways to make your Web page more than a Net brochure. In this chapter, you will learn the fundamentals of the HTML FORM tags, a requirement for building a real interactive Web page.
In particular, you will learn about the following:
The HTML Form tag is the basis for passing data to your CGI programs on the server. When you create your CGI program, you also should be thinking about and creating the HTML Form tag that will pass the data to your CGI program.
Because your CGI program and the HTML form must work together, we will build them together over the next several chapters. The simplest HTML Form tag creates a Submit button and activates your CGI program on your server. Figure 4.1 is an example of this simple format. This is not much different than creating a link to your CGI program. The HTML required to generate Figure 4.1 is shown in Listing 4.1; lines 7 through 9 create the Form tag.
Figure 4.1. A Form tag with only a Submit button.
01: <html> 02: <head> 03: <title> Your First HTML FORM </title> 04: </head> 05: <body> 06: <h1> A FORM tag with only a Submit button </h1> 07: <FORM Method=GET Action="/cgi-bin/first.cgi"> 08: <input type="submit" > 09: </FORM> 10: <hr noshade> 11: <h1> The HTML required for this FORM </h1> 12: <table border = 10> 13: <td> 14: <xmp> 15: <FORM Method=GET Action="/cgi-bin/first.cgi"> 16: <input type="submit" > 17: </FORM> 18: </xmp> 19: <tr> 20: </table> 21: </body> 22: </html>
The HTML Form tag has the following syntax:
<FORM METHOD="GET or POST" ACTION="URI" ENCTYPE=application/x-www-form-urlencoded>
Line 7 is a sample HTML Form tag:
<FORM Method="GET" Action="/cgi-bin/first.cgi" >
Add an input type to this HTML, and you have an active form:
<INPUT type="submit">
Warning: The Form tag does not allow any space between the opening < and the beginning of the tag type. The tags <FORM" or <input don't work if entered as < FORM or < input.
The HTML Form tag begins with a Method attribute. The Method attribute tells the browser how to encode and where to put the data for shipping to the server. And, as you saw in Chapter 2, "Understanding How the Server and Browser Communicate," the method will be used to generate a request method line, telling the server what type of data to expect. No data is shipped with the form in Figure 4.1, so you can think of that form as working a lot like an SSI command.
Table 4.1 summarizes the details of the Method, Action, and Enctype fields of the Form tag. Appendix B presents a complete overview of the HTML form syntax.
Attribute |
Description |
|
ACTION |
The URI (which usually will be a CGI script) to which the form data is passed. The URI will be called regardless of whether there is any data as part of the submittal process. It is possible to omit a URI; in that case, the URI of the document the form is contained in will be called. The data submitted to the CGI script (URI) is based on the ENCTYPE and the method attributes. |
|
ENCTYPE |
Defines the MIME content type used to encode the form's data. The only valid type now is the default value "application/x-www-form-urlencoded". Because the default value is the only valid value at the moment, you do not need to include this attribute in your FORM tag. |
|
METHOD |
Defines the protocol used to send the data entered in the form fields. The two valid method protocols are Post and Get. Get is the default method, but Post has become the preferred method for sending FORM data. The Get method's data is shipped appended to the end of the request URI, and it is encoded into the Environment variable QUERY_STRING. The Post's data is appended after the response headers, as part of standard input. |
There are two ways, or methods, in which your data will be shipped or sent to your CGI program on the server. The first method sends the data with the URI. This is done when the HTML Form tag uses the Get method like the following:
<FORM METHOD="GET" ACTION="A CGI PROGRAM">
This method of sending data is called the Get method. Pretty profound, huh? The other way of sending data has just as outlandish a name. It's called the Post method. Bet you can't figure out what's different here:
<FORM METHOD="POST" ACTION="A CGI PROGRAM">
That's what you get when you let the entire Internet community in on your design. Everybody on the Net contributes and you get these simple, unimaginative constructs. On the positive side, you'll probably have no problem remembering the Get and Post method names (unlike some of those names I had to remember for my biology 101 class).
So what's the difference between the Get and Post method, you ask? Well, here's the answer short and sweet.
The Get method sends your URI encoded data appended to the URI string. The URI encoded data and any path information are placed in the environment variables QUERY STRING and PATH INFO. Environment variables are covered completely in Chapter 7, "Building an On-line Catalog," but this chapter also examines the QUERY STRING.
URI encoding is very important and also is covered in detail later in this chapter. The examples I have included here include the complete CGI and HTML to enable you to see all the details. As you go through each example, you will learn about each of these topics and see how to apply them in a real example.
The Post method also URI encodes your data. However, it sends your data after all the request headers have been sent to the server. It includes the request header content length so that your CGI program can figure out how much data to read. Chapter 5, "Decoding Data Sent to Your CGI Program," gives you some examples of the Post method.
I told you it would be short and sweet, but don't worry; that's just a brief introduction. The details are covered quite well as we go through these next few chapters.
Generating Web pages on-the-fly only means using some type of program to send the Web page HTML back to the client or browser. Remember, normally the client clicks on a link, or a URI, and that identifies a file on a server. The server finds the file, generates the correct response headers, and sends the fileusually the HTMLback to the client.
So what's so different about generating a Web page on the fly? Not much. The server will get the request in for a CGI program, just as if it were going to get an HTML file. When it goes to get the file (your program), several things will happen:
Figure 4.2 is the Web page generated on-the-fly when the Submit button was clicked on the form in Figure 4.1. The Perl code that generated this Web page on-the-fly is shown in Listing 4.2. This example is as simple as it gets, but it illustrates the basics of CGI programming. You can take this program shell and build on it to generate much more complex CGI programs.
Regardless of how complex your programs get, the basics will remain the same:
Figure 4.2. A Web page generated from first.cgi.
01: #! /usr/local/bin/perl 02: print "Content-type: text/html\n\n"; 03: print <<'ending_print_tag'; 04: <html> 05: <head> 06: <title> My first CGI </title> 07: <background="#000000" text="#FF0000" > 08: </head> 09: <body> 10: <h1> My First CGI </h1> 11: <em> HELLO, INTERNET! </em> 12: <hr noshade> 13: Watch out cyber space, another programmer is on the loose ;-) 14: </body> 15: </html> 16: ending_print_tag
CGI programming is not like HTML programming. At some point, you have to start writing and understanding some type of programming language. That, of course, is why you're reading my book instead of one of the many on HTML. You probably already have some HTML books, and they might even include some CGI programming introductions in them.
What I am going to do throughout this book is to help you understand the most popular programming language on the net: Perl. I will focus on the aspects of Perl that will help you with CGI programs. You won't get a complete education in Perl, but the point is you don't have to be a Perl expert or a professional programmer to become a CGI programmer. Not with my book anyway!
As I introduce new CGI programs, I will give a detailed discussion of the Perl code in each program. This book will be enough to enable you to generate your own Web pages from your own CGI programs. As you get more sophisticated in your programming, you probably will want to by a programming book on Perl. I recommend Teach Yourself Perl in 21 Days, by Dave Till, published by Sams Publishing and Programming perl, by Larry Wall and Randal L. Schwarts, one of the nutshell handbooks from O'Reilly & Associates, Inc.
Your first CGI program, appropriately named first.cgi, does the minimum required of a CGI program as outlined here:
Note: OK, I admit it. I'm a programmer and I love having fun with variable names. Geeks are like that; they have fun with the stupidest things. Every time I get to write your first CGI program, knowing that the program name is first.cgi, I get a little smile. Hey, you gotta get your fun where you can. My programming buddy, Burton, calls it whistling while you work. I like to whistle.
Again, because this is your first CGI program, let's go over in detail the Perl code that makes this simple thing work.
As you go over the details of the code, you will learn the following:
Line 1 in Listing 4.2, #! /usr/local/bin/perl, tells the server what type of script language you are using and gives the directory where the Perl interpreter is located on my server. Your server might be different, but this is the default directory path and is likely to be the same on your server.
I use Perl throughout this book, but you could use the Bourne shell, or C shell scripting languages. Actually, there are lots of choices, including compiled languages like C. Perl is very popular and powerful, so we will stick with Perl.
Warning: The #! is a special directive to the preprocessor, and it must not have any space between it and the left column. A space after the #! is okay.
Line 2 of Listing 4.2 tells the server what type of data it will be sending to the browser. The server will add any additional response headers required to send the attached HTML. Also notice in line 2 the closing \n\n; two CRLFs are required to close the header request/response line sequence.
Don't forget the ending double newlines on the last response header. And don't get confused by the blank line between lines 2 and 3. That blank line is just for my visual convenience. It has zero impact on what is output from your first CGI program.
Line 3 in Listing 4.2 demonstrates one of the nice features of Perl. The ending_print_tag that follows the << tells Perl to print everything that follows the <<'print_tag' until it finds the print_tag flush against the left margin. So lines 4 through 15 are printed to standard output, without requiring a print statement on every line.
That was a nice, simple, straightforward, and pretty dull example. But dull examples have their place. It made a good introduction, and now I can show you how to make things a little more interesting.
Why do I think that was dull? Well, you might just as well have sent that Web page using an HTML file. Part of the reason for building Web pages on-the-fly is to create Web pages with variable data in them.
You don't want to send the same Web page back to every client. You want to customize your Web page for every different client. You do this by sending variables or variable data in your Web page. The format I showed you in first.cgi won't do that. Figure 4.3 is an example demonstrating variable interpolation. The top half of Figure 4.3 is the result of sending interpreted variables. The bottom half is what happens when variable interpolation is turned off. Listing 4.3 contains the Perl code used to generate this Web page.
Figure 4.3. A Web page showing variable interpolation.
The difference between the top and bottom half of the page shown in Figure 4.3 is called variable interpolation. Obviously, you want variable interpolation, so how do you get it? The difference is only the type of quotation character you use in your print string. In general, this is true with most Unix scripting languages. The different quotation types are explained in the following list:
As you go through the details of the Perl code in Listing 4.3, you will see examples of each of these quotation-mark techniques.
01: #!/usr/local/bin/perl 02: print "Content-type: text/html\n\n"; 03: 04: $MyDate = `date`; 05: 06: chop $MyDate; 07: 08: print <<"ending_print_tag"; 09: <html> 10: <head> 11: <title>CGI using Variables inside double quotation marks </title> 12: <background="#000000" text="#F0F0F0" > 13: </head> 14: <body> 15: <h1> CGI using variables inside double quotation marks </h1> 16: <p> 17: <em> HELLO, INTERNET! </em> 18: <br> 19: Today is $MyDate. 20: <hr noshade> 21: ending_print_tag 22: 23: print <<'ending_print_tag'; 24: <h1> CGI using variables inside single quotation marks </h1> 25: <p> 26: <em> HELLO, INTERNET! </em> 27: <br> 28: Today is $MyDate. 29: <hr noshade> 30: Watch out cyber space, another programmer is on the loose ;-) 31: </body> 32: </html> 33: ending_print_tag
Notice line 4,
$MyDate = `date`;
that the variable $MyDate is set from the system command `date`. I access the system command by including it in single, back quotation marks (`system_command`). This tells Perl to execute the enclosed command. The assignment statement = tells Perl to assign the output of the system command to the variable $MyDate on the left-hand side of the equal sign (=).
Line 8,
print <<"ending_print_tag";
tells Perl to print (as described earlier), but the double quotation marks also tell Perl to interpret any variables it encounters within the print string. $MyDate therefore converts the contents of the variable Sun Sep 3 10:48:58 CDT 1995.
The single quotation marks in line 23,
print <<'ending_print_tag';
tells Perl not to interpret anything inside the print string. The variable $MyDate therefore is printed, and not its contents.
Congratulationsyou've made it through the basics of CGI programming. Now it's time to get a little fancier. The first thing you need to do is introduce the Input HTML tag and its valid fields. The HTML Input tag has the format <INPUT TYPE="field">. The field value defines what "type" of data is visible on your Web page form. This is the basis for all your data entry and the real jumping-off point for building professional interactive Web pages. Table 4.2 is the basis for the examples in the remainder of this chapter and Chapters 5 and 6. Each of the different fields presents a totally different entry form on your Web page. That makes the HTML Input tag, in my own humble opinion (IMOHO), the most important HTML tag available. Take a few minutes to read through this table. Remember that I will step through each of these input fields in an example in this book.
Field |
Description |
|
Checkbox |
A two-state field: Selected or Unselected. The name/value pair associated with this attribute is sent to the CGI program only if Selected. A name/value pair can default to Selected by adding the attribute Checked. |
|
Hidden |
The Hidden field is not visible on the form and is frequently used to maintain state information. |
|
Image |
This acts just like a Submit button but includes the location from where the image was selected (or clicked on). |
|
Password |
The same as text, except that each character typed is echoed as an asterisk (*) or space ( ) character. |
|
Radio |
The radio button allows only one of several choices to be selected. Only one Name/Value pair is valid for a radio selection set. A default radio selection can be made by adding the Checked attribute. |
|
Reset |
When selected, all fields of the form are reset to their default values. |
|
Submit |
Visible as a selection button with the default name of Submit Query. The name can be changed with the Name field. When selected, the URI of the Action field is requested, and the form's input data is passed to the Action URI. If the Name field is used, the value of the Name field also is passed to the CGI program. This enables the CGI to distinguish between multiple Submit buttons on one form. |
|
Text |
A single line of text entry. You can set the Size of the window displayed with this attribute and the Maxlength of the data acceptable. |
The Text field creates a single-line text entry window on your Web page form. Your Web page user can enter any keyboard data she wants from this window. After your customer presses Enter, the data is URI encoded and sent to the CGI program defined in the Action field of the opening FORM tag. Using the Enter key to send the data entered on your form only works if there is only one text-entry field on your Web page form. If you have more than one text-entry field, you will need to use the Submit Input field. (URI encoding and the Submit field are covered later in this chapter.) Figure 4.4 shows an entry form with only one text-entry field, and Listing 4.4 shows the HTML for this form.
The syntax of the Text field follows:
<INPUT TYPE=TEXT SIZE="a number" MAXLENGTH="a number" NAME="some name" VALUE="optional initial value">
Figure 4.4. A single window text-entry form.
01: <html> 02: <head><title>Entering data from a single line text input </title></head> 03: <body> 04: <h1>Depress the ENTER key to submit your name to our list</h1> 05: Please register your name using the following window. 06: <form action="/cgi-bin/first.cgi"> 07: <input type=text name="enter" SIZE=20 Maxlenth=30 value="Eric Herrmann"> 08: </form> 09: </body> 10: </html>
The Size field defines how large a text-entry window will appear on your form. With most browsers, you can enter more data than is available in the window. The text will just scroll off the left side of the entry window. This way, if one of your clients has a long name, he still can enter his name in a smaller window.
The Maxlength field is handy to use when you have CGI programs that are interfacing with a database. Frequently, the fields in database programs need to be limited to some maximum value. You might have a database that takes only 20 character names. Limit the amount of data that will be sent to your CGI program by setting the Maxlength field to 20. That means your CGI program doesn't have to check for entries to it that are too large. It's just one less thing to have to worry about.
One of the most important fields is the Name field. The name you assign this field will be used in your CGI program to identify which incoming data belongs with which entry field. Data is passed to your CGI program as name/value pairs. The name is the variable name used in your CGI program. The contents or "value" of the name field is the data that was entered in your text-input window.
The Value field is optional. It defines initial data to go into the entry window. If you put the value="some text" field in your Input tag, "some text" will show up in the entry window whenever the form is loaded or the Reset button is selected. You can see an example of this in Figure 4.5.
The returned Web page from the text-entry example in Figure 4.4 is in Figure 4.5. Notice that in the Location field, you can see the name/value pair data. I call this the YUK! factor. This is the data passed to the server URI encoded. Also notice that the space between "Eric Herrmann" has been replaced with a plus sign (+). This is part of the URI encoding that is covered in detail shortly.
Sending data to your CGI program is what it's all about. And unless every form you create has only one entry field, you must use the Submit button to get the data to your CGI program. Whenever your form has more than one <INPUT type=text> tag or the type is anything besides TEXT, the Enter (carriage return) key will not submit the data on the form.
The SUBMIT INPUT TYPE format is similar to the TEXT INPUT TYPE:
<INPUT TYPE=SUBMIT NAME="get_price" value="Get Current Qoute">
The SUBMIT INPUT TYPE appears on your form as a button. If you look back at Figure 4.1, notice that the button is named Submit Query. This is the default for the <INPUT type="SUBMIT">. If you don't give a value definition, the button is named Submit Query. You can change the name of the button by giving it a VALUE, as I have done on line 33 of Listing 4.5. You also can give your Submit button a name. It makes sense to give your button a name if you have more than one button on your form. This way, your CGI program can tell from which Submit button the data is coming.
In this section, I will show you a couple of tricks I use to make my Web pages just a little more spiffy.
First, I worry about the layout of the Web page. I like to get as much data as is reasonable in front of my clients during the loading of that first computer screen. If I can manage it, I want them presented with all the essential data in one screen. Use common sense with this guideline; crowding a screen with too much data probably is worse than too little data. The other thing I like is having my entry forms aligned neatly. The example presented later in this section shows you some simple techniques using HTML tables to accomplish these goals.
Next, I worry about speed. Sometimes it's a good ideaand not too hardto use non-parsed headers (nph) CGI programs to speed up your Web page. The example here uses an nph-CGI program to help with speed, form refresh, and the YUK! factor.
Finally, this example begins the introduction to data encoding. It uses the Get method to send your data to the server. So we'll talk about the Get method and what happens with your URI encoded data.
In addition to all these things, Figure 4.6 shows the immediate power of the text-entry field. Except for the use of the Submit button, I only use the Text input type for this registration form. The HTML for Figure 4.6 is shown in Listing 4.5.
Figure 4.6. A Registration form using only text entry.
01: <html> 02: <head><title> HTML FORM using Text Entry</title></head> 03: <body> 04: <h1> A FORM using the Get method for text entry </h1> 05: 06: <hr noshade> 07: <center> 08: 09 : <FORM Method=GET Action="/cgi-bin/nph-get_method.cgi"> 10: <table border = 0 width=60%> 11: <caption align = top> <H3>Registration Form </H3></caption> 12: <th ALIGN=LEFT> First Name 13: <th ALIGN=LEFT colspan=2 > Last Name <tr> 14: 15: <td> 16: <input type=text size=10 maxlength=20 name="first" > 17: <td colspan=2> 18: <input type=text size=32 maxlength=40 name="last" > <tr> 19: <th ALIGN=LEFT colspan=3> 20: Street Address <td> <td> <tr> 21: 22: <td colspan=3> 23: <input type=text size=61 maxlength=61 name="street"> <tr> 24: <th ALIGN=LEFT > City 25: <th ALIGN=LEFT > State 26: <th ALIGN=LEFT > Zip <tr> 27: <td> <input type=text size=20 maxlength=30 name="city"> 28: <td> <input type=text size=20 maxlength=20 name="state"> 29: <td> <input type=text size=5 maxlength=10 name="zip"> <tr> 30: 31: <th ALIGN=LEFT colspan=3> Phone Number <tr> 32: <td colspan=3> <input type=text size=15 maxlength=15 name="phone" value="(999) 999-9999"> <tr> 33: <td width=50%> <input type="submit" name="simple" value=" Submit Registration " > 34: <td width=50%> <input type=reset> <tr> 35: </table> 36: </FORM> 37: </center> 38: <hr noshade> 39: </body> 40: </html>
If making your entry form look professional is important to you, this exercise will help explain how to line up your text-entry fields even if your form does not always have the same number of columns.
I like the Table attribute because it enables me to build a well-aligned entry form. The browser helps me by looking at the number of columns my table has in it and then evenly spacing those columns across the screen. This is nice, except when I want the columns to line up and I have a different number of columns in each row, as shown in Figure 4.6.
I can trick the browser into lining up my columns if I always give the last column a column span equal to the remaining number of columns, as in this example:
Lines 17 and 18
<td colspan=2> <input type=text size=32 maxlength=40 name="last" > <tr>
and Line 31
31: <th ALIGN=LEFT colspan=3> Phone Number <tr>
These lines force the ending column equal to the remaining maximum number of columns in a table.
Tables work by the browser making two passes through your table definition. On the first pass, the browser counts the number of rows and columns (among other things). On the next pass, it fills in the rows and columns aligning them, across your screen, based on the largest number of columns in the table. In this case, the maximum number of columns is three. So, on the first row of this table where there are two columns, made up of the First Name and the Last Name entry fields, I set the column span of the Last Name column to 2. This makes the browser line up the second column with column 2 of the other three column rows, instead of trying to center the columns.
Use this formula:
remaining_cols = max_cols [ms] used_cols
Therefore, if you apply the formula to the previous example, it works out as illustrated here:
max number of colums = 3, max_col number of columns used = 1, used_cols number of remaining columns = 2, remaining_cols = max_cols - used_cols
If you apply the formula to the Phone Number row, because no columns are used on the Phone Number row, colspan=3.
The other field that helps alignment in this example is the Align=LEFT field in the table header <th> or table data <td> fields. You can align left, right, or center on your table, depending on what looks best.
And finally a pure Netscapism: the <center> ... </center> HTML+ tag that centers the entire table on the page. I'll accept flames for this, but I like the cool extensions that Netscape gives me. The browsers that don't support the center aspect just see the table on the left of the Web page, which is okay.
There are at least two reasons to use NPH scripts in this example. One exists all the time and, after seeing how easy NPH scripts are to use, you might decide to use NPH scripts on a regular basis.
Everything has its pros and cons. CGI programs require more of your server resources than plain HTML files. They make your server work harder. I can hear it now! "What do I care? It's only a machine." True, but be kind to your computer and it will be kind to you.
The more you make your server work, the slower your Web pages are returned to your clients. You can help your server by not requiring it to parse the response headers. It's not very hard and eases the load on your machine.
If you'll recall from Chapter 2, "Understanding How the Server and Browser Communicate," the server normally parses your CGI returned headers and generates any additional required response headers. This takes time and, in this case, has an additional unwanted result (which is discussed in the next section).
Besides slowing down the return of your Web page, the URI encoded data appears in the location field of the returned Web page.
Remember the basics of CGI programming:
So your CGI program tells the server what to do and then sends some data. This usually means sending a confirmation notice or just resending the registration form.
Your user gets the benefit of a confirmation notice but the URI encoded data gets appended to your CGI URI and is made visible to the person registering. It just looks ugly. Listing 4.6 contains the returned URI when the registration form is returned.
http://www.accn.com/cgi-bin/nph-get_method.cgi?first=Eric&last=Herrmann& street=255+S.+Canyonwood+Dr.&city=Dripping+Springs&state=Texas&zip=78620& phone=%28512%29+894-0704&simple=+Submit+Registration+
YUK!
So for this example, I used the non-parsed header CGI nph-get_method.cgi shown in Listing 4.7.
01: #! /usr/local/bin/perl 02: $date = `date`; 03: print<<"END" 04: HTTP/1.0 204 No Content 05: Date: $date 06: Server: $SERVER_SOFTWARE 07: MIME-version: 1.0 08: 09: END
Warning: To make the non-parsed header script work, it must begin with nph-.
The most important part of this CGI script is line 4:
HTTP/1.0 204 No Content.
This is the status response header discussed in Chapter 2. The value of 204 tells the browser that there isn't anything to load with this response header, so leave the existing Web page displayed.
I also return the date, the server type, and the MIME-version response headers, but the CGI works without these headers. All that is required is the Status response header of 204 and a blank line.
The server does less work, the form doesn't get reloaded, and there's no YUK! factor.
We'll revisit this example in Chapter 5, using a different method that doesn't have the speed advantage but takes care of the YUK! factor and the lack of a confirmation notice.
All these examples have used the Get method to gather and send your data to your CGI program on the server. The Get method for sending form data is the default method for sending data to the server. Besides the YUK! value of the Get method, it has another problem. The URI-encoded string passed to your server is limited by the input buffer size of your server. This means that the URI-encoded string can get too big and lose data. That's bad.
The data entered on your form is URI encoded into name/value pairs and appended after any path information to the end of the URI identified in the Action field of your opening FORM tag.
Name/value pairs are the basis for sending the data entered on your Web page form to your CGI program on the server. They are covered next in detail. The browser takes the following steps to get your data ready for sending to the server:
The data after the question mark is referred to as the query string.
Whether or not you use the Get method, the URI encoding of the query string is consistent for all data passed across the Net. The QUERY_STRING, by the way, is one of the Environment variables discussed in Chapter 7, "Building an On-line Catalog."
Listing 4.8 is the data from the registration form. You can see the name/value pairs separated by the ampersand (&) and identified as pairs with the equal sign (=).
QUERY_STRING first=Eric&last=Herrmann&street=255+S.+Canyonwood+Dr.& city=Dripping+Springs&state=Texas& zip=78620&phone=%28512%29+894-0704&simple=+Submit+Registration+
In the example, there is no path information, so the query string begins immediately after the target URI, nph-get_method.cgi, is identified.
All the data input from a form is sent to the server or your CGI program as name/value pairs. In the registration example, you only used text input, but even the Submit button is sent as a name/value pair. You can see this at the end of the line in Listing 4.8. The Submit button name is "simple" and the value is "Submit Registration." Notice that case is maintained in the value fields.
Name value pairs always are passed to the server as name=value and each new pair is separated by the ampersand (&) name1=value1&name2=value2. This arrangement enables you to perform some simple data decoding and have a variable = value already built for your BOURNE or C-SHELL script to use. Using Perl, you can separate out name value pairs with just a little bit of effort. Input decoding is covered in Chapter 5.
Notice in line 16,
<input type=text size=10 maxlength=20 name="first" >
that the name attribute is added to the input type of text. If you are familiar with programming, the name is the formal parameter declaration and the value, whether given by default or by entering data into the entry field, is the actual parameter definition.
Put into other words, the name is your program's way of always referring to the incoming data. The Name field never changes. The data associated with the Name field is in the value portion of the name value pair. The Value field changes with every new submittal. In the example first=Eric name value pair, the name is first and the value is ERIC.
Just remember that whether you use text entry, radio buttons, checkboxes, or pull-down menus, everything entered on your Web page form is sent as name/value pairs.
Path information can be added to the action string identifying your CGI program. You can use path information to give variable information to your CGI program. Suppose that you have several forms that call the same CGI program. The CGI program could access several different databases, depending on which form was submitted.
One way to tell your CGI program which database to access is to include the path to the correct database in the form submittal.
You add path information in the Action field of the opening HTML Form tag.
First, you identify your CGI program by putting into the Action field the path to your CGI program and then the program name itselffor example,
<FORM METHOD=GET ACTION="/cgi-bin/database.cgi/">
Next, you add any additional path information you want to give your CGI program. So, if you wanted to add path information to one of three database in the earlier URI, it would look like
<FORM METHOD=GET ACTION="/cgi-bin/database.cgi/database2/">
The path information in this example is database2/.
When the Submit button is pressed, the browser appends a question mark (?) onto the Action URI and then the name/value pairs are appended after the question mark.
By now, you have figured out that in order to send your data from the browser to the server, some type of data encoding must have occurred. This is called URI encoding; I use the term URI encoding because, as discussed in Chapter 1, URL and URI are synonymous and the NCSA gurus use URI in their standards documents.
The convention of URI encoding Internet data was started to handle sending URIs by electronic mail. Part of the encoding sequence is for special characters like tab, space, and the quotation mark ("). E-mail tools have problems with these and other special characters in the ASCII character set. Next, the URI gets really confused if you used the reserved HTML characters within a URL. So if the URI you're referencing includes restricted characters like spaces, they must be encoded into the HEX equivalent.
So why do you care about URI encoding? Other than the fact that I have been talking about it all chapter long? Well, for two reasons really:
So what is this set of characters that cannot be included in your URI? One of the simple characters is the space character. If you own a Macintosh, spaces in file names are a common and convenient feature of the Apple operating system. However, when shipped on the Net, they confuse things. If you have a file name called Race Cars, for example, you need to encode that into Race%20Cars.
The % (percent sign) tells the decoding routine that encoding has begun. The next two characters are HEX numbers that correspond to the ASCII equivalent value of space.
If you were trying to send HTML tags as part of your data transfer, the < and > tags would need to be encoded. They encode as %3C for < and %3E for the >.
Note: If you are unfamiliar with HEX, it is only another numbering system with values ranging from 0 to 15, where the numbers 10 through 15 are encoded as the letters A through F. So, the HEX range is 0 through F. Your encoding always begins with a % and then two HEX numbers. You don't really need to understand HEX values any better than that; just read the numbers from the table and encode them as needed.
Table 4.3 lists the ASCII characters that must be encoded in your URI. It has both the decimal and HEX values. The decimal values are included only for information. They can not be used as encoding values; you must use the HEX values to URI encode these characters.
Character |
Decimal |
Hex |
|
Tab |
09 |
09 |
|
Space |
16 |
20 |
|
" |
18 |
22 |
|
( |
40 |
28 |
|
) |
41 |
29 |
|
, |
44 |
2C |
|
. |
46 |
2E |
|
; |
59 |
3B |
|
: |
58 |
3A |
|
< |
60 |
3C |
|
> |
62 |
3E |
|
@ |
64 |
40 |
|
[ |
101 |
5B |
|
\ |
102 |
5C |
|
] |
103 |
5D |
|
^ |
104 |
5E |
|
` |
106 |
60 |
|
{ |
113 |
7B |
|
| |
114 |
7C |
|
} |
115 |
7D |
|
~ |
116 |
7E |
In addition to the reserved characters listed here, there are several other characters that should be encoded if you don't want them to be interpreted by your server or client for their special meaning:
If you want to look at the gory details of MIME/URI encoding, you can get RFC 1552, the MIME message header extensions document off the Net. It has the encoding format in Section 3 and is available with the other Internet RFC documents at
http://ds.internic.net/ds/dspg1intdoc.html.
So now you know the basis for encoding all the data. Remember that all data sent on the Net is URI encoded. The steps used for getting your data encoded follow. These rules work for both the Post and the Get method:
In this chapter, you learned how to build simple HTML forms and then how the data entered on the form is sent to your CGI program.
The HTML FORM tag is the basis for passing data to your CGI programs on the server.
The HTML FORM tag has the following syntax:
<FORM METHOD="GET or POST" ACTION="URI" ENCTYPE=application/x-www-form-urlencoded>
The Method attribute tells the browser how to encode and where to put the data for shipping to the server.
There are two ways your data will be shipped or sent to your CGI program on the server:
The basics of CGI programming follow:
The HTML Input attribute of the Form tag accepts several different field values. Each field value defines a different type of user input format. The HTML Input tag has the format <INPUT TYPE="field">. The text field is the most commonly used field type. It creates a single-line, text-entry window on your Web page form. Regardless of the input type you choose, all of the data input from a form is sent to the server or your CGI program as name/value pairs. Name/value pairs always are passed to the server as name=value, and each new pair is separated by the ampersand (&).
The data entered on your form goes through these formatting steps before being sent to the server:
Q: I've seen forms without a method defined. How does that work?
A: Because the Get method is the default method if a method is not defined, the Get method is used. So,
<FORM ACTION="/cgi-bin/first.cgi">
is the same as
<FORM METHOD=GET ACTION="/cgi-bin/first.cgi">
Q: What's the difference between a Submit button and a link?
A: A link, of course, is an HTML anchor with a hypertext reference usually to an HTML file. But you could link to a CGI program. So what's the difference?
Well, let's look at it from the Submit button viewpoint. Could you call an HTML file from the Submit button? Well, yes. "Eric," you say, "you're confusing me."
Okay, I'm sorry. The difference is the "submittal" of the data. The link doesn't send any data.
The Submit button causes the browser to do the following:
So, I really could have answered the question with this:
But I don't think it would have been quite as clear.
Q: My first CGI program doesn't work. What's the matter?
A: When your CGI programs don't work, run through this checklist. Usually you'll discover its one of these problems: