Search This Blog

Wednesday, February 3, 2010

HTML (Web) Forms

As previously mentioned, there are two main methods by which you can interact with an online application running within your browser: click a link or submit a form. Clicking a link can request a page from the Web server, and if the application developer included data in a query string, clicking the link also sends that data. However, when you fill out a form and submit it, you have a much richer opportunity to send data to the Web server. Although some of the form fields may be preset (such as data in a query string) others (such as text and textarea fields) give you a great deal of control over the data you send. HTML forms are therefore used extensively to create user interaction capability that mimics the kind of interaction displayed in desktop applications.

HTML Form Elements

The HTML specification describes HTML elements related to forms, including the <form> element (begins and ends a form), the <input> element (makes several types of form field, including text fields, radio buttons, submit buttons, and so on), the <textarea> element (makes a text field with multiple columns and line), and the <select> element (makes drop down and static list boxes).


Each of these elements also has attributes. For example, the <form> element includes an attribute named method. The method attribute can be set to post (like this: method="POST") within the beginning form tag, and it makes the HTTP request's method be POST when the form is submitted.
Although it's common to refer to an HTML element as a tag, the term tag refers only to the beginning or ending HTML delimiter. For example, <p> is the beginning tag of the HTML element P (for paragraph) and </p> is the ending tag of this element. Together, the <p> and </p> tags make up the P element. By the way, the text between them (that is displayed in your browser as a paragraph) is their content.
When properly written, HTML form elements combine to create a very powerful means of user interaction for online applications. In the following sections each form field element and its attributes are discussed in detail.

The <form> Element

What happens when you submit a form in HTML? The user fills out the various text boxes and clicks a Submit button when ready; the information that is supplied is then bundled up in one of the two ways and sent to the Web server. The Web server can then pull out this information, and supply it to the PHP script engine. PHP manipulates this information and sends it back as part of the HTTP response to the browser. All you need to do to make a form is create a pure HTML Web page with opening and closing <form> tags. Any controls such as text field, check boxes, and radio buttons that are placed between the <form> tags, automatically become part of the form that is sent to the Web server. For example:

<form name="myform" action="myform_processor.php" method="POST">
<input type="text" name="first_name">
<input type="submit" name="button" value="Send Response">
</form> 
 
In this example, the form is named myform, and when it's submitted it sends the request (using the POST method) and all the data filled out by the user to the PHP file named myform_processor.php for processing. Of course you can send the request to any page or file you choose, even back to the page the user is currently on, keeping in mind that the page being requested should have code for accepting the data sent and working with it.

The first <input> element uses the type attribute to specify the type of form field to display, in this case a text box. Although the name of the form (myform) is not very important in this example, the name of the first <input> element is extremely important, because PHP automatically makes a variable named $first_name from the name you give the <input> element, and sets that variable equal to the value entered in the field by the user. The variable is part of the $_GET or $_POST array, depending upon the submission method you set for the form.

The second <input> element has a type of submit, so it renders as a Submit button. The value attribute is set to Send Response, so it displays a caption of Send Response on top of the Submit button. Neither its name nor value is very important in this example (so far as PHP processing is concerned), but you should know that both the name and value are available to your PHP program for processing when the form is submitted.

Essentially, when a user fills out the form and submits it, the names and values of the form fields become variables available to the receiving PHP program (specified in the action attribute of the <form> element). When you understand that, the full range of user interaction with HTML forms becomes apparent.

Here are a few tidbits of useful information about HTML forms:
  • You can have more than one form in a single Web page, and each one (and its form fields) can be submitted independent of the others.
  • Names are not generally important for forms, unless you are using JavaScript to decide which one to work with or submit.
  • Values submitted in forms are always strings, although once they get to your PHP program they may be converted to any data type as you use them.
  • Not all form field names and values become available to your PHP program when a form is submitted. For example, only the value of the selected radio button (in a group of radio buttons) is submitted.

Attributes of the <form> Element

The <form> element has a whole host of attributes, but you can get by using only two of them, action and method. Other attributes, such as id, class, dir, lang, language, name, style, and title are universal to most or all HTML tags, and shouldn't need further explanation. The more obscure attributes accept-char and enctype, which specify the character sets and the mime-type of the form data are outside the scope of this overview, although you'll learn more about enctype in Chapter 7. There is also a target attribute that, like its namesake in the <a> element, enables you to specify a frame or window in which to display the Web page that is sent back in response to the form's submission.
The action Attribute
The action attribute tells the server which page to go to once the user has clicked a submit button on the form. It doesn't matter whether this page is pure HTML, PHP, or uses any server-side technology, as long as the page exists on the Web server. It can be used as follows to link to an HTML page:

<form action="myprogram.php">
...
</form> 
 
However, when you supply a PHP page as part of the action attribute, what you're actually doing is sending the information entered into this form to the PHP script engine for processing, thereby allowing your PHP application on the server to work with user-supplied data. The action attribute just tells the server which page to go to next—if you saved the earlier page as myprogram.html instead of myprogram.php, the page wouldn't be sent to the PHP script engine and nothing at all would be displayed unless PHP has been configured to parse .html files. Later you'll see what the PHP script engine does when it receives the form.
The method Attribute
The method attribute controls the way that information is sent to the server. As mentioned previously, it can do this in one of the two ways, using either the GET or the POST methods (they are case-insensitive, but the convention is uppercase). The GET method is the default; you use these methods as shown here:

<form action="myprogram.php" method="GET">

or

<form action="myprogram.php" method="POST"> 
 
There are actually more than two values you can supply to the method attribute: HEAD, PUT, LINK, UNLINK, OPTIONS, DELETE, TRACE, and CONNECT. However, these options are not commonly used, and you rarely need to use them, so there's no further discussion of them here. You will, however, want to take a closer look at GET and POST.
The GET Value
The GET value of the method attribute tells the browser to append the values the user placed on the form to the URL. Like the query string attached to a URL in a link, the browser adds a question mark to the end of the URL to denote where the URL finishes and the form information starts. The information entered into the form is then transmitted as name/value pairs. If the GET method is specified in the method attribute of the <form> element, the browser automatically appends the information to the URL when it sends the page request to the Web server.

And just like a query string in a link, you can add more than one name/value pair to a URL if you separate each pair with an ampersand (&). With two name/value pairs, the end of the URL might look like this after being submitted:
As mentioned earlier, the name/value pairs are very similar to variables. In fact, once they have been passed to the Web server for processing, PHP makes them available as variables. So, if you submitted your form to the Web server, and moved to another page, the name/value pairs would be available in the PHP script as variables (as part of the $_GET array).

Occasionally, you might want to pass spaces in the values that make up the query string. For instance, if you have a form that includes a <textarea> element and someone had typed in the line, "I would like to see a dynamic menu in operation," there are several spaces that need to be represented. In this case the addition operator would replace the spaces, as shown here:
Some of you are wondering, "But what happens if you want to put an addition operator in the <textarea>? How is that represented within a query string?" The character or operator in question has to be replaced by a code, which signifies the particular character. This is known as URL encoding.

URL Encoding

There is a set of characters that can't appear in a URL, and therefore by association, can't appear in a query string either, so they have to be URL encoded.


The encoding process requires you, the user or developer, to do precisely nothing. It's all done for you. The Web browser takes the offending character, whether a bracket or an addition sign, and replaces it with a code value (when sending to the server), and takes the URL encoded value and replaces it with the appropriate character (when displaying in your screen). The URL encoded value is always the same (for example, a blank space is always be represented by %20). The following table lists the most common characters and their code values.

Character
URL Encoding
Tab
%09
Space
%20
!
%21
"
%22
#
%23
%
%25
&
%26
(
%28
)
%29
+
%2B
,
%2C
.
%2E
/
%2F
:
%3A
;
%3B
<
%3C
>
%3E
=
%3D
?
%3F
@
%40
\
%5C

Some of these characters have to be encoded, or they would adopt another meaning in the query string (as you saw earlier, the addition operator is used to denote a space in the query string, and the question mark denotes the start of a query string).

The previous query string with the URL code value for a space in place of the addition operator would look like this:
You'll see an example of GET in action a little later. For now, take a look at POST.
The POST Value
One disadvantage you might have discerned from query strings is the rather public nature of their transmission. If you don't want the information sent to appear in the URL, then you will have to rely on the POST method instead. This works almost identically to the GET method; the difference is that the information in the form is sent in the body of the HTTP request, rather than as part of the URL. This means that it isn't visible to everybody, because it isn't attached to the URL. POST can also allow a greater amount of information to be transmitted. There is a physical limit to the amount you can transmit as part of a URL.
Do You Use GET or POST?
There's a mixture of opinion on this one; some people say you should almost never use the GET method because of its insecurity and limit on size; others maintain that you can use GET to retrieve information, but POST should be used whenever you modify data on the Web server. There are no hard and fast rules, though, and these are just guidelines.

One disadvantage of POST is that pages loaded with it cannot be properly bookmarked, while pages loaded with GET contain all the information needed to reproduce the request right in the URL. In many cases you can bookmark the result of a form submission (a search on Alta Vista, for example) by using the GET method, and that's why most search engines use GET. Another disadvantage of POST is that the method itself isn't secure—while the information is placed in the HTTP body and isn't immediately visible, the information isn't encrypted and is still easily obtained by a hacker. To make sure it is secure, you would need to use a secure connection to a secure server.

Which method you use depends on what you want the form to do. If you do use GET, be aware of its shortcomings and its indiscreet nature. If you use POST, beware that it can't be bookmarked by search engines, and just because it is more discreet doesn't mean it is more secure.

HTML Form Fields (Controls) and PHP

With an understanding of the process under your belt, you're ready to look at the most common HTML form field controls you can use to collect information in a form, and see how you can use PHP to get at this information afterward. By the way, you can use the terms form field, control, and form element interchangeably; they all mean the same thing.

All of the following examples in this section will require two Web pages. The first page retrieves information posted by the user, and the second sends the information from the Web server and scripting engine back to the browser. Note that it is entirely possible to combine a form and it's response into a single file, but this gets cumbersome when your programs become a bit more complex. In fact, PHP programs often contain many files making up an application.


The first Web page doesn't have to contain any PHP script at all. In fact, on many sites, the Web page that contains the form will be pure HTML and will have the suffix.htm or.html. That's the format for all of the following examples (although later on, as your applications become more complex, the format will deviate quite a bit). Obviously there is no need to send any information to the PHP scripting engine, because if it contains no PHP, then this will just add overhead (add to the time it takes to process and generate the Web page to be returned to the browser).

Let's get started by looking at the most common HTML form controls.

Text Fields (Text Boxes)

Text fields or text boxes are probably one of the most familiar controls you will come across on any form. They are created using the <input> element and by setting the type attribute to text.

<input type="Text" name="TextBox1"> 
 
Their advantage is that they can take whole sentences of text from the user. This makes them ideal for open-ended questions, where there can be a vast and unpredictable range of possible answers.

Back to the practical side of things, the following example is a Web page in which you take the user's favorite author and display it to the screen on the next page.

Try it Out: Use Text Fields
Start example
  1. Open your text editor and type in the following HTML:
    <html>
    <head><title></title></head>
    <body>
    <form method="GET" action="text.php">
    Who is your Favorite author?
    <input name="Author" type=" text">
    <br>
    <br>
    <input type="submit" value="submit">
    </form>
    </body>
    </html>
  2. Save it as text.html, and close the file.
  3. Start a new file in your editor and type the following code:

    <html>
    <head><title</title></head>
    <body>
    Your favorite author is:
    <?php
    echo $_GET['Author'];
    ?>
    </body>
    </html>
  4. Save it as text.php, and close the file.
  5. Open text.html in your browser and type a name in the text box .
  6. Click the Submit button, and the author name you supplied is displayed.

How it Works

First of all, note the URL at the top of the screen in Figure 3-4. A query string has been appended to the end of the page named text.php. That was added by the Web browser, because you instructed it to do so in the program text.html with the following HTML:

<html>
<head></head>
<body>
<form method="GET" action="text.php">
Who is your favorite author?
...

Setting the method attribute to GET has passed the form information as a query string, rather than hiding it. Take a look at the query string at the top of Figure 3-4. It reads:

?Author=Juan+Rulfo 
 
You already know that query strings are made up from name/value pairs. In this example, Author is the name and Juan Rulfo is the value in this example. The query string picks up Author as its name from the following highlighted line in your first program, text.html:

Who is your favorite author?
<input name="Author" type="text">
<br> 
 
The name attribute of the <input> tag has set this control to have the name Author. You added the value when you entered the name of your favorite author in the text field.
The second program, text.php, is actually one line of text, followed by one line of PHP:

Your favorite author is:
<?php
echo $_GET['Author'];
?> 
 
The line of PHP displays the contents of the variable called $_GET['Author']. Nowhere within the code have you physically created this variable; it's automatically part of the $_GET array. What you've created is an HTML text box and given it the name Author. When the form went to the Web server and the PHP script engine, the PHP engine created the $_GET array with a variable named $Author. If you'd called your text box Name, then your variable would have been called $_GET['Name']. That's all this example program does.

Why this Example Might Not be Working for You

If the query string is passed, but it fails to return an author name or returns with a warning, you've most likely confused the cases in your two programs:



If, for example, you had the following line in text.html, with a lowercase a:

<input name="author" type="text"> 
 
whereas in text.php you had $_GET['Author'] with an upper case A:

echo $_GET['Author']; 
 
the program will break because variable names in PHP are case-sensitive. Although HTML itself isn't case-sensitive, PHP is taking the variable name from the name you assigned to the HTML text field, so it is creating the PHP variable $_GET['author'], not $_GET['Author']. You must make sure that the name of the HTML text field and the name you use in your PHP script are absolutely identical, case and all.

Text Areas

If you want to have a text field that allows multiple lines to be typed, you need a completely different HTML control: the <textarea> element. Use the element's attributes to set the size and number of rows and columns of the control, among other features. For example,

<textarea name="WebSites" rows="30" cols="50"> 
 
creates a text area named WebSites whose size is 30 rows by 50 columns. A text area is designed to take whole sentences from the user. Its advantage is that you can set the size, and it can take many lines of text. <textarea> requires a closing tag, and you can place default text for each line inside the tags.

Ready to try using a text area?

Try it Out: Use Text Area
Start example
  1. Start your Web page editor and type the following:

    <html>
    <head><title></title></head>
    <body>
    <form method="POST" action="textarea.php">
    What are your favorite web sites?
    <textarea name="WebSites" cols="50" rows="5">
    http://
    http://
    http://
    http://
    </textarea>
    <br>
    <br>
    <br>
    <input type="submit" value="Submit">
    </form>
    </body>
    </html>
  2. Save it as textarea.html. Close the file.
  3. Create another file and type the following:

    <html>
    <head><title></title></head>
    <body>
    Your favorite web sites are:
    <?php
    echo $_POST['WebSites'];
    ?>
    </body>
    </html>
  4. Save this as textarea.php.
  5. Open textarea.html in your browser (see Figure 3-6) and type in the URLs of some of your favorite Web sites.
  6. When you're finished (you don't have to fill in all four sites), click the Submit button. 

How It Works

Not quite as neat and tidy as the previous example, is it? But don't let that distract you from an important point, which is the URL that reads:
There's no query string attached. And that's because in the first of these two programs you set method to equal POST.

<html>
<head><title></title></head>
<body>
<form method="POST" action="textarea.php">
What are your favorite web sites?
... 
 
You needed to make that change to ensure that your form details aren't freely visible. There's little else of particular interest on the Web page, apart from the <textarea> element:

<textarea name="WebSites" cols="50" rows="5">
http://
http://
http://
http://
</textarea> 
 
It's set to be five rows high, and 50 columns across to get it to the size you need. Unlike in normal HTML, the text inside the <textarea> element doesn't require line breaks (the <br> tag); it's enough to start it on a new line to get it displayed on a new line. The name of the textarea control is set to WebSites, and then in the second program (textarea.php), this variable is referenced in PHP as $WebSites, once again taking care to ensure the cases are identical:

...
Your favorite web sites are:
<?php
echo $_POST['WebSites'];
?>
... 
 
The entire contents of the <textarea> element are then dumped to the screen, but the carriage returns that separated them in the HTML page are automatically collapsed by the browser, along with any extra white space, to make the details fit in.

Check Boxes

A check box is another control that, like a text field, is created in HTML using the <input> element. It provides a single box that can be ticked or not, depending on the option chosen. It doesn't require any data from the user, other than a click in the check box, so any data this control contains is quite different from the text field. In HTML it looks very similar—the only difference is the type:

<input name="Choice" type="checkbox"> 
 
A check box is appropriate when you have a question that requires a strict yes/no answer. Check boxes also have a checked attribute, which takes no value. Supply this attribute in the control and the check box will be checked by default:

<input name="Choice" type="checkbox" checked> 
 
The control also has a value attribute set to on by default.

Some of the advantages of check boxes over other forms of input control aren't immediately obvious, but they become clear after you've used several of them. The following exercise utilizes just one check box and returns the contents of it to the screen.

Try it Out: Use a Check Box
Start example
  1. In you Web page editor type the following code:

    <html>
    <head><title></title></head>
    <body>
    <form method=" POST" action=" checkbox.php">
    Have you ever eaten haggis before?
    <input name="Choice" type="checkbox">
    <br>
    <br>
    <Input type="submit" value="Submit">
    </form>
    </body>
    </html>
  2. Save it as checkbox.html, and close the file
  3. Start a new file and type in the following:

    <html>
    <head><title></title></head>
    <body>
    <?php
    echo $_POST['Choice'];
    ?>
    </body>
    </html>
  4. Save it as checkbox.php, and close the file.
  5. Open checkbox.html in your browser and check the check box as shown in Figure 3-8.
  6. Click Submit. The choice echoed out is "on," as shown in Figure 3-9.
  7. Click your browser's Back button, uncheck the check box, and click Submit again. Because the box was unchecked this time, nothing shows up in the browser.

How it Works

Again, there's no query string on the end of the URL because you used the POST method to pass your form information to the Web server. You set this in the first of the two programs, checkbox.html:

<html>
<head><title></title></head>
<body>
<form method="POST" action="checkbox.php">

The check box form control is created with the <input> element:

Have you ever eaten haggis before?
<input name="Choice" type="checkbox"> 
 
In checkbox.php, you call the PHP variable, which has exactly the same name as the control you set in checkbox.html:

<?php
echo $_POST['Choice'];
?> 
 
The only difference is that the variable is now created with a value that wasn't assigned by you. If the check box was ticked by the user, then it contains the value on. If it wasn't, then it contains nothing at all.

Multiple Check Boxes

What happens if you want to use more than one check box? If you're familiar with radio buttons, you know that selecting one radio button in a group of radio buttons automatically moves the choice from whatever button was selected before to your current selection. Check boxes don't work like that, and their advantage is that each check box is counted as an individual entity—you can have several check boxes ticked, or you can have none checked at all.

Let's modify the previous example to include several check boxes.

Try it Out: Use Multiple Check Boxes
Start example
  1. Open your Web page editor and save the following as checkboxes.html:

    <html>
    <head><title></title></head>
    <body>
    <form method="POST" action=" checkboxes.php">
    Have you ever eaten haggis before?
    <input name="Choice1" type="checkbox" value="Haggis">
    <br>
    Have you ever eaten snails before?
    <input name="Choice2" type="checkbox" value="Snails">
    <br>
    Have you ever eaten locusts before?
    <input name= "Choice3" type="checkbox" value="Locusts">
    <br>
    <br>
    <input type="submit" value=" Submit">
    </form>
    </body>
    </html>
  2. Close the file, then create a new file and type in the following:

    <html>
    <head><title></title></head>
    <body>
    <?php
    echo "$_POST[Choice1]<br>";
    echo "$_POST[Choice2]<br>";
    echo "$_POST[Choice3]<br>";
    ?>
    </body>
    </html>
  3. Save the file as checkboxes.php.
  4. Open checkboxes.html in your browser (see Figure 3-10).
  5. Select one or more options and click Submit. The program displays your choice(s) (see Figure 3-11).

How it Works

The value attribute for each check box is set in the first program:

Have you ever eaten haggis before?
<input name="Choice1" type="checkbox" value="Haggis">
<br>
Have you ever eaten snails before?
<input name="Choice2" type="checkbox" value="Snails">
<br> 
Have you ever eaten locusts before?
<input name="Choice3" type="checkbox" value="Locusts"> 
 
This has the effect of setting a value for each check box after it has been checked. For example, if the Choice1 check box is ticked, it will have the value of Haggis (rather than the default on), and that value is then passed on to the $Choice1 variable in your checkboxes.php page. If the check box isn't ticked, nothing is passed on to the PHP variable of the same name, In the second program, checkboxes.php, you display the contents of the three variables set independently in the first program like so:

echo "$_POST[Choice1]<br>";
echo "$_POST[Choice2]<br>";
echo "$_POST[Choice3]<br>"; 
 
Each of three check box controls was named and set independently. It's possible to set all three inputs to have the same name, but that might not yield the results you expect. For example, change the following code in the program checkboxes.html:

Have you ever eaten haggis before?
<input name="Choice" type="checkbox" value="Haggis">
<br>
Have you ever eaten snails before?
<input name="Choice" type=" checkbox" value="Locusts">
<br>
Have you ever eaten locusts before?
<input name="Choice" type=" checkbox" value="Snails"> 
 
Run the program again and select more than one option. Surprised at the outcome? You get only one answer, the last selected option in the list. What happens is that PHP stores each occurrence of the variable over whatever the variable contained before. Whichever is the last check box to be set, that's the last value the variable is set to. What you can do, though, is add a pair of square brackets ([]) to the name of each HTML control:

Have you ever eaten haggis before?
<input name="Choice[]" type="checkbox" value="Haggis">
<br>
Have you ever eaten snails before?
<input name="Choice[]" type="checkbox" value="Snails">
<br>
Have you ever eaten locusts before?
<input name="Choice[]" type="checkbox" value="Locusts">

This creates an array of variables within the $_POST array. To distinguish the different variables, PHP adds a number, which acts as a unique identifier, to the end of each variable name. The first version of the variable has a zero in square brackets ([0]) added to the end, the second has a one in square brackets([1]), and third version has a two in square brackets([2]).

To get PHP to display the contents of these variables, refer to the variable explicitly with its full name, such as $_POST[Choice][0]. In $_POST[Choice][0] you find the value Haggis if Haggis was selected. In variable $_POST[Choice][1] you find the value Snails if Snails was selected, and so on for the rest of the HTML controls that share the same name. Without the square brackets, you can't create an array from an HTML form, although you can still create arrays as much as you like in your PHP program, as discussed in Chapter 2.

Radio Buttons

Radio buttons are the selfish cousins to check boxes. If you have a selection of answers or options but only one of the options can be selected at a time, then you should use radio buttons. Once again, radio buttons are created using the <input> element setting the type attribute to Radio.

<input name="Question1" type="radio" value="Porto"> 
 
Radio buttons, like check boxes, have a checked attribute in HTML, which again takes no value. If you supply this attribute in the control, the check box is checked by default:

<input name="Question1" type="radio" checked> 
 
If you supply no value for the value attribute, it is set to "on" by default.
Contrary to check boxes, to connect a set of radio buttons, you must supply each radio button in your group with the same name. For example:

<input name="Question1" type="radio" value="Porto">
<input name="Question1" type="radio" value="Lisbon">
<input name="Question1" type="radio" value="Madrid"> 
 
This method tells the Web server that all of these buttons are connected. If you give each radio button control a different name, the user can select each option independently, just like a check box.

Try it Out: Use Radio Buttons
Start example
  1. Open your Web page editor and type in the following code:

    <html>
    <head><title></title></head>
    <body>
    <form method="GET" action="radio.php">
    What is the capital of Portugal?
    <br>
    <br>
    <input name= "Question1" type="radio" value="Porto">
    Porto
    <br>
    <input name="Question1" type="radio" value="Lisbon">
    Lisbon
    <br>
    <input name="Question1" type="radio" value="Madrid">
    Madrid
    <br>
    <br>
    <input type="submit" value="Submit"> </form>
    </body>
    </html>
  2. Save the file as radio.html, and close it.
  3. Create a new file and type in the following:

    <html>
    <head><title></title></head>
    <body>
    <?php
    echo "You selected the answer: $_GET[Question1]";
    ?>
    </body>
    </html>
  4. Save the file as radio.php.
  5. Open radio.html in your browser and select an answer (see Figure 3-12).
  6. Click Submit and view the results of the choice you made (see Figure 3-13).

How it Works

The method of transmission is changed to GET, so the query string is visible once more. A questionnaire is actually the one time when this might be useful. It confirms the answer that's selected, which would admittedly be more useful if the answer wasn't already displayed in the body of the page. That aside, take a quick look at the programs. The first program, radio.html, sets three radio button controls. They all have the same name, Question1, but with three different values to reflect the different answers:

<input name="Question1" type="radio" value="Porto">
Porto
<br>
<input name="Question1" type="radio" value="Lisbon">
Lisbon
<br>
<input name="Question1" type="radio" value="Madrid">
Madrid 
 
Then in the second program, radio.php, you only need to display the contents of the one variable because there can only ever be one answer to the question:

<?php
echo "You selected the answer: $_GET[Question1]";
?>

List Boxes

List boxes or drop-down list boxes are controls that typically display several items in a list. Sometimes they have an arrow next to them that enable the user to scroll down to additional items. They work a little different in HTML because they're created with two elements: <select> and <option>. Essentially, they provide the same functionality as the radio buttons, given that usually you can only select one item from a predetermined list of options.
The <select> element that creates the list box encloses a number of <option> elements, each of which contains the text that corresponds to an item on the drop-down list:

<select name="Price">
    <option>Under $5,000</option>
    <option>$5,000–$10,000</option>
    <option>$10,000–$25,000</option>
    <option>Over $25,000</option>
</select> 
 
However, there are times when being able to select several items is appropriate, and you can allow multiple items to be selected by adding the multiple attribute to the <select> element. This gives PHP two things to think about. You'll deal with both of these options in the following example in which you get information from the user about the price of a car he wants to purchase and its engine size. The first question allows only single answer, and the second allows multiple items, which can be selected by holding down the Shift key.

Try it Out: Out Use a List Box
Start example
  1. Open your Web page editor and type in the following:

    <html>
    <head><title></title></head>
    <body>
    <form method="POST" action="listbox.php">
    What price of car are you looking to buy?
    <br>
    <br>
    <select name="Price">
        <option>Under $5,000</option>
        <option>$5,000-$10,000</option>
        <option>$10,000-$25,000</option>
        <option>Over $25,000</option>
    </select>
    <br>
    <br>
    What size of engine would you consider?
    <br>
    <br>
    <select name="EngineSize[]" multiple>
        <option>1.0L</option>
        <option>1.4L</option>
        <option>1.6L</option>
        <option>2.0L</option>
    </select>
    <br>
    <br>
    <input type="submit" value="Submit">
    </form>
    </body>
    </html>
  2. Save the file as listbox.html and close it.
  3. Create another new file and type in the following:

    <html>
    <head><title></title></head>
    <body>
    <?php
    echo "Price Range: $_POST[Price]";
    $Choice0 = $_POST['EngineSize'][0];
    $Choice1 = $_POST['EngineSize'][1];
    $Choice2 = $_POST['EngineSize'][2];
    $Choice3 = $_POST['EngineSize'][3];
    echo "<br>Engine Size(s): $Choice0";
    echo "$Choice1";
    echo "$Choice2";
    echo "$Choice3";
    ?>
    </body>
    </html>
  4. Save this file as listbox.php.
  5. Open listbox.html in your browser and select one option from the top box, and one or more from the bottom list box (see Figure 3-14).
  6. Click Submit. Figure 3-15 shows an example result.

How it Works

In the first program, listbox.html, a list box is created with four items, and multiple selections are allowed. The <select> element's name attribute is set to Price:

<select name="Price">
    <option>Under $5,000</option>
    <option>$5,000-$10,000</option>
    <option>$10,000-$25,000</option>
    <option>Over $25,000</option>
</select>

In the second program, listbox.php, the name attribute is referred to with the PHP variable $-POST[Price]:

<?php
echo "Price Range: $_POST[Price]";
... 
 
There's absolutely nothing out of the ordinary going on here, and it should look very familiar up to this point. It's on the second list box in listbox.html that things depart from the norm:

<select name="EngineSize[]" multiple>
    <option>1.0L</option>
    <option>1.4L</option>
    <option>1.6L</option>
    <option>2.0L</option>
</select> 
 
Well, actually everything looks pretty much the same apart from the top line, which sets the name attribute to be EngineSize[]. Attaching the brackets([]) to the end of a control name is a cue to PHP to treat it as an array.

$Choice0 = $_POST['EngineSize'][0];
$Choice1 = $_POST['EngineSize'][1];
$Choice2 = $_POST['EngineSize'][2];
$Choice3 = $_POST['EngineSize'][3];
echo "<br>Engine Size(s): $Choice0,";
echo "$Choice1,";
echo "$Choice2,";
echo "$Choice3,";

As mentioned earlier, during the creation of an array, PHP creates a new variable of the same name with an index number bolted on. There are four items on the list, so there are four index numbers. The contents of each one must be displayed because each index number refers to an item in the array. Array indexes always start at zero, so $EngineSize[0] refers to the first option in the list, 1.0L. It contains this item only if that option is selected, otherwise it contains the contents of the first <select> option chosen on that page.

In this example, this option is selected, so $EngineSize[0] does indeed contain the value 1.0L. The same goes for $EngineSize[1] which relates to the second option. $EngineSize[2] and $EngineSize[3] don't contain anything because no more values were selected in the list box. If only one option were selected, then only $EngineSize[0] would contain a value. Only if all four options were selected would $EngineSize[2] and $EngineSize[3] contain any values. If only the last two items were selected, then the variables $EngineSize[0] and $EngineSize[1] would contain 1.6L and 2.0L, respectively. $EngineSize[2] and $EngineSize[3] still wouldn't contain any values. To easily display the values with the echo statement, variables for each choice were created and set them to the string values in the array variables.
Please remember that if you have set error reporting to on so that you can view errors from your browser ("display_errors = On" must be set in your php.ini file,) you will display some warnings for the unselected values of the engine size because not all the $_POST['EngineSize'][] variables will be set.

Hidden Form Fields

There are times when you want to take information contained in a Web page, and pass it to another Web page without requiring any input from the user. There's another setting for the <input> control that enables you to pass information in a field just as if it were a text box but keeping the control and its contents hidden. This is known as a hidden form field (or hidden control).

Hidden form fields come into play in a slightly different manner than the controls already demonstrated. They're probably more useful on PHP pages that contain forms because you can use them to send information contained within PHP variables. Here's a typical hidden form field on a form:

<input type="hidden" name="Hidden1" value="Secret Message"> 
 
There's no screenshot of this because the control wouldn't appear on the page. Any form that submitted it though would have a variable called $Hidden1 that contains the text Secret Message. To use the hidden form field in a PHP page, you can write the whole HTML form in echo() statements, transferring the contents of PHP variables via HTML controls as shown here:

<?php
$Message1="This message is invisible";
echo "<form>";
echo "<input type='hidden' name='Hidden2' value='$Message1'>";
echo "<input type='submit' value='Submit'>";
echo "</form>";
?> 
 
This entire HTML form is written in PHP statements and it enables you to create a variable called $Hidden2 and transfer the contents of $Message1 into it. Of course, this is not the only way to keep data available across form submissions or page requests; cookies, sessions, and so on are discussed later on in this chapter.

Now for an example that takes the contents of a <select> list box and displays the user's choice on the next page. The preceding process is used to write the HTML form in PHP echo statements as well.

Try It Out: Use the Hidden Form Field
Start example
  1. Open your Web page editor and type the following:

    <html>
    <head></head>
    <body>
    <?php
    $Messase1 ="Bugs Bunny";
    $Message2="Homer Simpson";
    $Message3="Ren & Stimpy";
    echo "<form method='GET' action='hidden2.php'>";
    echo "Which of the following would win in a shootout?";
    echo " <select name='ListBox'>";
    echo "<option>$Message1</option>";
    echo "<option>$Message2</option>";
    echo "<option>$Message3</option>";
    echo "</select><br><br>";
    echo "<input type='hidden' name='Hidden1' value='$Message1'>";
    echo "<input type='hidden' name='Hidden2' value='$Message2'>";
    echo "<input type='hidden' name='Hidden3' value='$Message3'>";
    echo "<input type='submit' value='Submit'>";
    echo </form>";
    ?>
    </body>
    </html>
  2. Save the file as hidden.php and close it.
  3. Start a new file and type in the following:

    <html>
    <head><title></title></head>
    <body>
    <?php
    echo "The three options were:<br>";
    echo "$_GET[Hidden1]<br>";
    echo "$_GET[Hidden2]<br>";
    echo "$_GET[Hidden3]<br>";
    echo "<br>You selected:<br>";
    echo "$_GET[ListBox]";
    ?>
    </body>
    </html>
  4. Save the file as hidden2.php and close it.
  5. Open hidden.php in your browser and make a selection (see Figure 3-16).
  6. Click Submit to view the results (see Figure 3-17).

How it Works

Once you get over the process of creating the HTML form in echo statements rather than straight HTML code, this is really very straightforward. The main difference is that you can leave out the apostrophes in the variable name in the array. Three variables are created to form the basis of the <select> list box:

$Message1="Bugs Bunny";
$Message2="Homer Simpson";
$Message3="Ren & Stimpy"; 
 
They are respectively $Message1, $Message2, and $Message3. Next, the HTML form is created using echo statements. Absolutely nothing differs from a normal HTML form, except that when you want to use quotation marks in the HTML, you have to use single quotation marks and not double ones or you'll break the echo statement. The first line just tells you to send the form contents to hidden2.php via the GET method:

echo "<form method='GET' action='hidden2.php'>";
Some explanatory text is displayed and then the <select> list box is started:
echo "Which of the following would win in a shootout?";
echo "<select name='ListBox'>"; 
 
It gets three options, the contents of the variables $Message1, $Message2, and $Message3, respectively.

echo "<option>$Message1</option>";
echo "<option>$Message2</option>";
echo "<option>$Message3</option>"; 
 
The <select> list box is closed and a couple of line breaks are added:

echo "</select><br><br>"; 
 
Then the three variables already used are passed as hidden form fields to the form:

echo "<input type='hidden' name='Hidden1' value='$Message1'>";
echo "<input type='hidden' name='Hidden2' value='$Message2'>";
echo "<input type='hidden' name='Hidden3' value='$Message3'>"; 
 
The three variables will turn up on the form as $Hidden1, $Hidden2, and $Hidden3, respectively. A Submit button is added to the form, and the form is closed:

echo "<input type='submit' value='Submit'>";
echo "</form>"; 
 
The second PHP page just displays the contents of the controls created in the first page. The contents of the three hidden form fields are displayed first:


echo "The three options were:<br>";
echo "$_GET[Hidden1]<br>";
echo "$_GET[Hidden2]<br>";
echo "$_GET[Hidden3]<br>";

This is useful because normally the contents of the entire list box aren't transferred across. Only the option selected by the user is passed over to the next PHP page. However, sometimes you want to have all of the list box contents available in your PHP page. This is one effective method for transferring this type of information.

The last lines just display the contents of selection made by the user.

echo "<br>You selected:<br>"; 
echo "$_GET[ListBox]"; 
 
Hidden form fields are used to perform this type of task later in this book.

Password Fields

Passwords are essentially text fields that blank out the input with asterisks when the user types in text. They store and transmit information in the same way as text fields:

What is your password? 
<input name="Password" type="password"> 
 
There's no difference in the processing between text and password types of text fields, so no example is provided here. If you want to see one in action, just go back to the previous example text.html and change the type to password. However, if you choose to transmit this information, using GET, then notice that the password is not encrypted in the query string and will be visible to all and sundry. That isn't to say once again that POST is a secure method of sending data, just that the information isn't as immediately visible. If you want security you must use something like SSL (Secure Sockets Layer) to actively encrypt your data.

Submit Buttons and Reset Buttons

Submit buttons have been used copiously throughout this chapter, so there's no need for an example that demonstrates how they work. However, there are a couple of points to note. First, what happens if you need more than one submit button in a form? In this case you will have to set the name and value attributes of the Submit buttons on your page as well. For example:

<input value="Button 1 pressed" type="submit" name="Submit1">
<input value="Button 2 pressed" type="submit" name="Submit2"> 
 
This, as you might expect, creates variables in PHP that PHP can pick up. In fact, this code would create one variable in PHP depending on which button is pressed. If you press Submit1 then a variable called Submit1 is created within the $_GET or $_POST array. If you press Button 2, then Submit2 is created. The contents of Submit1 are Button 1 pressed, while the contents of Submit2 are Button 2 pressed. There's actually nothing useful to be done with this yet, so there's no example now.

Secondly, the Submit button offers no respite if you type in the wrong information. Although you can't actually undo information sent via the Submit button, the Reset button control offers a little help because it can be used to set the state of all controls on the form to their initial state.

<input type="reset">

Using Values Returned From Forms in Your PHP Scripts

You've seen all manner of controls, and how PHP handles their contents, but you still haven't done anything practical with the contents other than to dump them into another Web page. Admittedly, without any of the features that you'll learn about in the next chapter, manipulating the contents of variables is hard. However, you learned about mathematical and string operators in the last chapter and you can combine that knowledge with concepts presented in this chapter.

In the last example in this chapter, you'll create a loan application form that asks for the amount of money that a user wants to borrow, and calculates the amount of money that a fictional bank called NAMLLU can offer that person based on his age and salary. You give the user a simple yes or no answer at the end of the calculation.

Although the program's loan calculation acceptance formula might seem complex, it's really quite straightforward (and isn't based on any company's formula). The loan amount for a person is calculated using three numbers, as follows:
  • Salary Allowance variable: The user's annual salary divided by 5.
  • Age Allowance variable: The user's age divided by 10; round the result down to the nearest whole number; and then subtract one.
  • Loan Allowance variable: The Salary Allowance variable multiplied by the Age Allowance variable.
The Age Allowance variable automatically excludes anyone who is younger than 20, because the formula always return a zero, and anything multiplied by zero is zero. Here's an example of figuring the Loan Allowance variable for a 19-year-old, where First figure is the Salary Allowance variable:

First figure * (19/10 - (19 Modulus 10) /10))-1 
 
Remember that the Modulus operator is used to return the remainder from a division sum. This calculation works out to:

First figure * (1.9 - 0.9) -1 
 
which works out to:

First figure * 0 
 
For any age under 20, the Loan Allowance variable always returns zero because no matter what the Salary Allowance variable is, when multiplied by a zero, it returns zero.
Here's another example of how this works: A 57-year-old user whose annual salary is $50,000 applies for a loan through your loan application form.
  • His Salary Allowance variable is 50,000/5 = 10,000.
  • His Age Allowance variable is (57/10 - (57 Modulus 10)/10)) - 1 = 4.
  • His Loan Allowance variable is 10,000*4 = $40,000 (Salary Allowance variable multiplied by Age Allowance variable).

If the Loan Allowance variable is more than the amount the person wants to borrow, you say yes; otherwise, you say no.

Try It Out: The Loan Application Form
Start example
This program needs two pages (and nearly all of the controls introduced in this chapter). The first page takes the loan details from which you get the person's first name, second name, age, address, salary, and the amount he wants to borrow. The second page, the PHP page, does the calculation for you and delivers a verdict.
  1. Open your Web page editor and type in the following:

    <html>
    <head><title></title></head>
    <body>
    <b>Namllu Credit Bank Loan Application Form</b>
    <form method="POST" action="loan.php">
    First Name:
    <input name="FirstName" type="text">
    Last Name:
    <input name="LastName" type="text">
    Age:
    <input name="Age" type="text" size="3">
    <br>
    <br>
    Address:
    <textarea name="Address" rows="4" cols="40">
    </textarea>
    <br>
    <br>
    What is your current salary?
    <select name="Salary">
    <option value=0>Under $10000</option>
    <option value=10000>$10,000 to $25,000</option>
    <option value=25000>$25,000 to $50,000</option>
    <option value=50000>Over $50,000</option>
    </select>
    <br>
    <br>
    How much do you want to borrow?<br><br>
    <input name="Loan" type="radio" value="1000">Our $1,000 package at 8.0% interest
    <br>
    <input name="Loan" type="radio" value="5000">Our $5,000 package at 11.5% interest
    <br>
    <input name="Loan" type="radio" value=" 10000">Our $10,000 package at 15.0% interest
    <br>
    <br>
    <input type="submit" value="Click here to Submit application">
    <input type="reset" value="Reset application form">
    </form>
    </body>
    </html>
  2. Save this file as loan.html. Close it.
  3. Create a new file and type the following:

    <html>
    <head><title></title></head>
    <body>
    <b>Namllu Credit Bank Loan Application Form</b>
    <br>
    <br>
    
    <?php
    $SalaryAllowance = $_POST['Salary']/5;
    $AgeAllowance = ($_POST['Age']/10 - ($_POST['Age']%10)/10)-1;
    $LoanAllowance = $SalaryAllowance * $AgeAllowance;
    echo "Loan wanted:$_POST[Loan]<br>";
    echo "Loan amount we will allow:$LoanAllowance<br><br>";
    if ($_POST|'Loan'] <- $LoanAllowance) echo "Yes, $_POST[FirstName]
    $_POST[LastName], we are delighted to accept your application";
    if ($_POST['Loan'] > $LoanAllowance) echo "Sorry, $_POST[First-Name]
    $_POST[LastName], we cannot accept your application at this time";
    ?>
    </body>
    </html>
  4. Save this file as loan.php.
  5. Open loan.html in your browser (see Figure 3-18) and supply some details.
  6. Click the Submit application button and you should see something like Figure 3-19.

How it Works

You'll have earned a break after examining these two programs. Although the first is lengthy, it isn't doing anything out of the ordinary, and certainly nothing you haven't already encountered in this chapter. The loan form (loan.html) contains eight controls. The first three are all text fields, used for accepting the first name, last name, and age of the applicant:

<input name="FirstName" type="text">
Last Name:
<input name="LastName" type="text">
Age:
<input name="Age" type="text" size="3"> 
 
You should be able to see now that they will create the variables $_POST[FirstName], $_POST[LastName], and $_POST[Age] on the PHP page.

The address is entered into a <textarea> control:

<textarea name="Address" rows="4" cols="40">
</textarea> 
 
This in turn creates a PHP variable $_POST[Address]. You don't make use of all of the PHP variables created in the form, but there are similar examples in later chapters and some of them are used there.


The next control is a drop-down list box, which contains a set of salary ranges:

<select name="Salary">
<option value=0>Under $10000</option>
<option value=10000>$10,000 to $25,000</option>
<option value=25000>$25,000 to $50,000</option>
<option value=50000>Over $50,000</option>
</select> 
 
You can't actually store a range as a value, so instead, the lowest value in the range is assigned as a particular value to each radio button. This creates just one PHP variable, $_POST[Salary], which holds the value associated with whichever range has been selected by the user. If there has been no range selected, the radio button returns no value. Notice that the first value is set to zero, and as before this zero in the formula ensures that anybody with a salary of less than $10,000 is automatically refused a loan. (I'm a bit mercenary!)
The next control is a group of three related radio buttons:

How much do you want to borrow?<br><br>
<input name="Loan" type="radio" value="1000">Our $1,000 package
at 8.0% interest
<br>
<input name="Loan" type="radio" value="5000">Our $5,000 package
at 11.5% interest
<br>
<input name="Loan" type="radio" value="10000">Our $10,000 package
at 15.0% interest
<br> 
 
These all have the same name, because the variable only ever needs to contain one value depending on what the user has selected. This group of three buttons creates just one PHP variable, $Loan.

The last two controls are a submit button and a reset button:

<input type="submit" value="Click here to Submit application">
<input type="reset" value="Reset application form"> 
 
The submit button utilizes the action attribute that was set at the top of the form, so it knows where to send the form:

<form method="POST" action="loan.php"> 
 
As you see, the first program stores and transmits the information in the form, but it's the second program, loan.php, that takes these values and performs some simple operations on them to approve or reject the loan claim. The first line creates a new variable, the Salary Allowance, which is the user's salary divided by five:

$SalaryAllowance = $_POST['Salary']/5; 
 
The second line calculates the more complex Age Allowance formula, which you want to return a whole number, based on the user's age divided by 10. If there is any remainder left over from the division, you remove it by rounding the answer downward to the nearest whole number. Use the modulus operator on the user's age to calculate the remainder on the user's age. Subtract one from the result to get the variable, as explained earlier. The final line returns a 0 if the user enters his age as a value between 0 and 19, a 1 if the age supplied is a value between 20 and 29, a 2 if the age supplied is a value between and 30 and 39, and so on. The result of this calculation is stored in the new $AgeAllowance variable:

$AgeAllowance = ($_POST['Age']/10 - ($_POST['Age']%10)/10)-1; 
 
Fortunately, the next line is much simpler. It takes the two figures just calculated, multiplies them together, and stores them in a new variable $LoanAllowance, which is the final figure for how large a loan the user is allowed to take out.

$LoanAllowance = $SalaryAllowance * $AgeAllowance; 
 
The next two lines just echo() a confirmation on the Web page of the amount supplied by the user for the loan he wants, and the amount of loan that you will allow:

echo "Loan wanted:$_POST[Loan]<br>";
echo "Loan amount we will allow:$LoanAllowance<br><br>"; 
 
The next two lines use the <= (less than or equals) operator, which enables you to make a decision based on the information you've been given. The operator determines whether the loan amount requested by the user is less than or equal to the amount that you (the bank) will allow. If it is, you display a message on the Web page saying that you're delighted to accept the application. This structure is discussed in detail in the next chapter; so don't worry it's covered briefly here.

The display message is also personalized with the names the user provided on the form:

if ($_POST['Loan'] <= $LoanAllowance) echo "Yes, $_POST[FirstName]
$_POST[LastName], we are delighted to accept your application"; 
 
The final line of PHP script handles the rejection situation—if the amount the user wants to borrow exceeds the amount the bank will authorize. It displays a message saying that the application is rejected.

if ($_POST['Loan'] > $LoanAllowance) echo "Sorry, $_POST[FirstName]
$_POST[LastName], we cannot accept your application at this time"; 
 
That's all there is to these programs. Oh, one tiny little detail: the nature of the information in a real-life application is sensitive, so use the POST method to transmit it. Remember, POST is only more discreet; hackers can just as easily hijack information sent via this method. For real security, use an SSL certificate to encrypt communications between the user and the Web server.

Possible Improvements to the Form

Of course, the form isn't perfect; indeed if you try hard enough, you can break it, or cause it to display illogical values. That's because there's no kind of validation performed on the values received from the user. What's to stop a user supplying a totally erroneous value for his age such as 965? You know it can't be true, but you can't stop it. In the next few chapters you'll examine ways of tightening this up, by checking the values and only allowing values within a certain range, or even that the user has actually supplied a value, but that's enough for now.