Program Input
On the Web, inputany data your program needs to process or know in order to perform its taskis gathered from an HTTP request. An HTTP request occurs whenever a user types in an address, clicks a link, or clicks a button on a Web page. The request contains information about the request, such as the desired file, any cookies that have been sent to the browser for that site, and any form fields that are being submitted to the server.
The request can be very complicated, however. Since PHP was created with Web programming in mind, it makes gathering this information less complex.
You still have to know a few things about the HTTP request because PHP divides the input it receives into the categories based on how they arrive in the HTTP request. Input is divided into three main categories: get, post, and cookie variables. You must know which category your variables are in to be able to access them.
NOTE
There is a more direct shortcut for accessing variables discussed later in this chapter, along with its advantages and disadvantages. However, make sure you understand this material before you try to use the shortcut.
For now, don't worry about the cookie variables category; it will be covered in Chapter 17, "Putting It All Together."
Get and Post Form Methods
You may recognize the other two categories, get and post, from your previous HTML experience; they are attributes used in the method tag of a form. Depending on which sort of form you use, you will need to use the corresponding category in PHP.
Get forms are commonly used for search queries and small amounts of information that may be exposed in the address bar of the visitor's browser. A get request is also made whenever a user clicks a link.
CAUTION
You should not use a get form when requesting a visitor's password or other sensitive information. Items from a get form will be in plain sight of anyone within sight of the visitor's monitor.
When information is sent to the server in a get request, PHP puts all of the form fields and their values in the appropriate input array, $HTTP_GET_VARS. So, to get the value of a field, use the value of $HTTP_GET_VARS with the field name as the key.
Let's take a look at an example. The following program generates a personalized greeting for a visitor:
<?php /* ch03ex10.php shows personalized greeting form */ ?> <html> <head><title>Welcome!</title></head> <body> <form action="ch03ex11.php"> What's your name? <input type="text" name="userName"> <input type="submit" value="Continue"> </form> </body> </html>
Since the form's method isn't specified and get is the default method, get is assumed. The PHP file can then find the value for the field in $HTTP_GET_VARS['name'], as shown in the following file:
<?php /* ch03ex11.php shows personalized greeting */ ?> <html> <head><title>Welcome!<title></head> <body> <h4> Welcome, <?= $HTTP_get_VARS['name'] ?>! </h4> </body> </html>
The username and password are shown to the user just as they were entered on the form.
Now let's take a look at using links to make get requests. When I refer to links, I'm not just referring to the HTML <a> tag. I'm also referring to addresses typed directly into a browser's location bar or the address specified in an <img> tag.
To investigate this further, let's create a single-question survey. The question, which could be inserted anywhere in an HTML file, should be set up similar to this:
<?php /* ch03ex12.php survey form */ ?> <html> <head><title>Survey</title></head> <body> Which animal do you like better? <a href="ch03ex12.php?answer=dogs">Dogs</a> or <a href=" ch03ex12.php?answer=cats">Cats</a> </body> </html>
Upon clicking one of the links, the visitor is taken to answerSurvey.php, which looks like this:
<?php /* ch03ex12.php - handles survey answers */ ?> <html> <head><title>Your Answer</title></head> <body> You said you like <?= $HTTP_GET_VARS['answer'] ?> the best! </body>
As you can see, get requests are handled precisely the same as those made with forms. You can also change the question file so that the answer is collected using a form instead of a link. Try this for practice.
Now that you know about get forms, let's take a look at the other form method. Post forms are used for larger amounts of data (such as detailed user information, e-mail messages, or file uploads) and data that should not be visible in the browser's address bar (such as passwords). An example of data being clearly visible in the browser's Address bar is given in Figure 3.3.
Figure 3.3 Sensitive information in a get request may be revealed in a browser's Address bar.
Let's try a practice problem. Yahoo!, Hotmail, and Excite all offer private services which require a username and password. In order to verify that a user is really the user he claims to be, services such as these must check that the login name and password are valid. For now, we'll just focus on collecting the data. The process of actually verifying the information is a separate concept, which will be discussed at various times later in this book, particularly in Chapter 6, "The if, elseif, and else Statements," and Chapter 13, "Creating Dynamic Content with PHP and a MySQL Database," when we discuss if statements and using databases, respectively.
The program will have two files: one to request the user's username and password and a second to retrieve that data.
The first file will contain a form that has its method set to post. If we don't set the method attribute, the username and password will be left out in the open in the user's address bar, which is considered to be a security risk. Anybody that happens to walk by the visitor's computer can see the password in the browser's Location or Address bar. Figure 3.3, shown previously, shows this vulnerability.
Here's the first file:
<?php /* ch03ex13.php login form */ ?> <html> <head><title>Authorization Required</title></head> <body> <form action="ch03ex14.php" method="post"> Username: <input type="text" name="username"><br> Password: <input type="password" name="password"><br> <input type="submit" value="Login"> </form> </body> </html>
That's not too complicated; it's just an HTML page with a form. Now we need to set up the file to accept the data this form posts. For now, we're going to set up our program to show the visitor the username and password he entered. To do so, we'll use the contents of the $HTTP_POST_VARS array because the information was posted with the post method.
Here's the second file, which handles the data posted from the first file:
<?php /* ch03ex14.php - shows the visitor what username and password he entered */ ?> <html> <head><title>Enter your password</title></head> <body> Username: <?= $HTTP_POST_VARS['username'] ?><br> Password: <?= $HTTP_POST_VARS['password'] ?> </body> </html>
This should look a lot like the $HTTP_GET_VARS example did; the only difference is that we've changed the method for the form, so we have to change which array we use in PHPthe two (the value of the form's method tag and the name of the script's input variable) must always correspond with one another.
For practice, try modifying this program to use get as the method.
TIP
You'll need to modify both files in order to make it work with the get method.
Once you've modified it and it's working, look at the address in your browser's Address or Location bar after you've posted the form. You should notice a string (such as "?username=joe&password=joepass") appended to the end of the filename. This is another illustration of why get forms and passwords aren't a good mixture.
Using Forms
Although creating HTML forms isn't technically a part of PHP, it is definitely a part of learning PHP. Since forms are just about the only way for your program to collect information from the user, you must use the form elements allowed by HTML to construct the most intuitive form possible.
TIP
The intuitiveness of a form is the overall effectiveness it has for the user. For example, using a single-line text input where the user will probably be entering a large amount of text makes it difficult for the user to read and edit what he's typing. In that case, it would be more effective to use a textarea.
The various form-input types will be discussed to help you create the most intuitive forms, which in turn makes your visitors experience more pleasing.
Form inputs allow the user to enter text and make selections. For example, if you wish to ask a user for his name, a simple text input is fine. The text input follows this syntax:
<input type="text" name="field_name" value="default_value">
The value attribute is optional; in most cases, it would be left blank. However, if you wish to suggest a value for the user's input, you can include the value="default_value" attribute and the value will appear in the field.
For example, to suggest a default value using a variable you already have (such as one that was entered from a previous form), you can specify the value attribute by outputting the variable's value with short equals tags, like so:
<?php /* ch03ex16.php default value example */ // Assume $user_name can come from a previous form submission; // it's specified here for clarity. $user_name = "John Doe"; // Print a form using this name as the default value for the user_name field ?> <form> <b>Name:</b> <input type="text" name="user_name" value="<?= $user_name ?>"><br> <input type="submit"> </form>
NOTE
Assuming PHP has its default configuration, you should be able to set the action attribute of this form to the name of the program file (such as ch03ex16.php) and the value of the field would be updated as the default value every time the submit button is clicked.
This example is primarily here to demonstrate that you can specify a dynamic default value, just as any other output can be dynamic.
There are several types of inputs for making selections. We'll look at radio and check box inputs first, then compare them to select inputs.
The radio input is used to ask the user to pick one item out of a list. The syntax follows this form:
<input type="radio" name="field_name" value="field_value">
In this case, the value attribute is not optional; if you don't specify it, the field will appear to be blank from within PHP, even if the option is selected. This type of input is best used in groups; the following example could be used to ask a visitor what his favorite pet is
What's your favorite pet?<br> <input type="radio" name="favorite_pet" value="dog">Dog<br> <input type="radio" name="favorite_pet" value="cat">Cat<br> <input type="radio" name="favorite_pet" value="camel">Camel<br> <input type="radio" name="favorite_pet" value="none">None<br>
Notice that all of the inputs have the same name; this is a feature of the radio input that allows the user to choose only one option, but it only works if the radio buttons all use the same name.
If you wish to get multiple answers from a user, you would need to use a check box input, which follows this syntax:
<input type="checkbox" name="field_name" value="field_value" checked>
Again, the value attribute must be included with this input. However, the checked attribute you see at the end of the tag is optional; if it's included, the check box will appear checked by default.
This type of input is commonly seen when you sign up for newsletters and free services online. These services gather information about the users they have so they can charge their advertisers more for targeted advertising. The following example demonstrates the common question, "What magazines do you subscribe to?"
What magazines are you currently subscribed to?<br> <input type="checkbox" name="us_news" value="true">US News <input type="checkbox" name="sports_illustrated" value="true">Sports Illustrated <input type="checkbox" name="national_geographic" value="true">National Geographic <input type="checkbox" name="time" value="true">Time
Notice that all of the name attributes are different; they cannot be the same or multiple selections would overwrite each other and only the last one would be retrievable from within PHP.
The select field allows similar data collection, using a smaller space. For example, listing all of the countries for the user to pick one could take up a lot of space on your form, making it seem longer than it really is. By putting all of the countries into one select input, the long list is compressed into one line. The syntax for a select input is
<select name="field_name" size="field_height" multiple> <option value="option_value">option_text</option> ... <option value="option_value">option_text</option> </select>
The value attribute is optional; if it is omitted, the text used for option_text will be used as the value as well (but option_text never overwrites a value specified in option_value). The multiple attribute is also optional; leaving it out forces the user to pick only one option. If specified, the size attribute determines how many options are visible at once. If the size is omitted, the input appears as a drop-down list; otherwise (if it is specified), the list appears in a scroll box.
Here's a very short example that could be used to ask a user what country he is from:
What country do you live in? <select name="country"> <option>China</option> <option>France</option> <option>Germany</option> <option>United Kingdom</option> <option>United States</option> </select>
Notice that the multiple attribute wasn't included because you only want to allow the user to pick one country. Also, the value attributes were omitted because the text found between the two option tags is all you need to know. (The value tags are often used to associate numeric codes that the program understands with textual names that the visitor understands.)
It's not always appropriate to limit the user to just one selection. To allow multiple selections, the multiple attribute must be specified. Once it is, the user can make multiple selections using Ctrl and Shift. The following input asks the user about his hobbies:
What are your hobbies?<br> <select name="hobbies[]" multiple> <option>Travel/Sightseeing</option> <option>Automotive/Cars/Hotrods <option>Sports/Fitness</option> <option>Reading</option> <option>Outdoors/Camping/Fishing</option> </select>
This input allows the user to select from zero to all of the options given.
CAUTION
Notice the brackets in the name attribute; since they are present, the hobbies variable in PHP will be an array, with each element being an element selected from the options list. If the brackets were left out, only the last option selected would be visible within PHP.
Let's say Automotive and Reading are the two options chosen from this list, and the form is submitted. In this case, the $hobbies array contains
Array( [0] => "Automotive", [1] => "Reading" )
The last method for gathering information is the textarea. The textarea is used to allow the user to type a large amount of text, such as a feedback message. Here is the basic syntax for a textarea field:
<textarea name="field_name" rows="field_height" cols="field_width">default_value</textarea>
Although the rows and cols attributes are optional, it's best to specify them. You need to experiment a little with these to get a feel for how they affect the size of the textarea. The default_value shown between the beginning and ending tags shows where you can suggest a default value for the textarea to contain. Because the textarea allows for multiple paragraphs, adding a value attribute is not appropriate; this is why the default value is specified between the textarea's opening and closing tags. If you chose to omit the default value, you still need to include the closing </textarea> tag.
There are two inputs to submit a form: submit and image. These inputs work about the same way, except the latter uses an image instead of a gray button.
Here's an example of each; these two uses are functionally equivalent:
<input type="submit" value="Submit"> <input type="image" src="/path/to/image.gif">
Your forms must always include a submit button or the form won't be very effective. Pressing Enter or using JavaScript works most of the time, but it's always preferable to have a button for those who can't use Enter or don't support JavaScript.
You might want to use this section as reference until you get used to creating forms (if you're not already used to it). With some practice, you'll have no trouble at all creating intuitive forms.