3.9 Working with Forms
Up to now, you have seen how to write simple PHP applications. However, for building interactive Web sites it is necessary to allow the user to insert data into so-called forms. The content of such forms can be transmitted to the server and a PHP script can react based on the data sent to it. Interacting with a Web server can be done with two methods called GET and POST.
3.9.1 GET and POST
The methods GET and POST are described in RFC2068, which is longer than 160 pages. In this section you learn about the main ideas behind GET and POST, and you learn to use these two methods efficiently.
3.9.1.1 GET
GET is the standard request method for retrieving data from a Web server. When calling a Web site, GET is used to get the document you have selected. Normally calls like that don't have side effects, and that is what GET should be used for. Browsers assume that GET has no side effects and if the page is not in the browser's cache any more, the page will be retrieved again. However, if the original request was via POST, the user would receive a message that the document is no longer in the cache (in section "Building Forms" in this chapter, you will learn to get around this problem).
3.9.1.2 POST
POST is the standard method for submitting data stored in a form to Web server. In the case of POST, the request always contains a body where the information related to the request is stored. This information is coded like a query string. Normally Web developers use POST even when no data on the server is modified.
3.9.2 Building Forms
After you have seen which methods can be used to retrieve data from a Web server, you have a look at a simple form that can be used to send text to a PHP file:
<html> <body> A Simple Form <br><br> <form action="reaction.php" method="POST"> <input type="text" name="field_1" size="10"><br><br> <input type="submit" name="submitbutton"> </form> </body> </html>
In line number 5 a form is defined. When the user clicks on the Submit button, the data will be sent to reaction.php. The form consists of two components. The first component is a text field called field_1. The second component is the button to submit the form. The end of the form is marked by </form>.
Let's start the script and see what the browser displays (see Figure 3.3).
Figure 3.3 A simple form.If you click the button, reaction.php will be started:
<?php if ($field_1) { echo "field_1: $field_1"; } else { echo "nothing has been passed to this script"; } ?>
The first thing done by the script is to see if $field_1 is defined. If the user has inserted data into the form, the variable will be defined in PHP automatically. In contrast to Perl, PHP programmers do not have to extract the variables from the query string themselves because everything is done by PHP.
If $field_1 is defined, the content of the variable will be displayed on the screen.
As you can see, retrieving data from a form is an easy task. In the next step you will see how more complex forms can be built with the help of HTML:
<html> <body> A more complex form <br><br> <form action="reaction.php" method="POST"> <input type="text" name="field_1" size="10"><br><hr> <input type="checkbox" name="box_1"> display time<br><hr> <input type="radio" name="myradio" value=1>Value 1<br> <input type="radio" name="myradio" value=2>Value 2<br> <input type="radio" name="myradio" value=2>Value 3<br><hr> <input type="password" name="passwd"> Enter passwords here<br><hr> <input type="file" name="filename"> enter the filename<br><hr> <input type="reset" name="resetbutton"> <input type="submit" name="submitbutton"> </form> </body> </html>
The first component defined in the form is a text field again. The length of the field is set to 10. In addition to the size of the field, it would also be possible to define the maximum length of the text the user is allowed to insert. This can be done by using maxlength. After defining the text field, a check box is defined. The name is set to box_1. After that you can see how radio buttons can be added to a HTML document. In the example you can see that myradio consists of three components. Only one of those three components can be activated. Depending on which of the three buttons is checked, the appropriate value is sent to reaction.php. If you need fields for inserting passwords, password will be the right type for you. While typing, the user will only see asterisks, so nobody can grab the user's password.
To select a file on the user's hard disk, the type called file can be used. File will create a text box and a button you can click if you need a window where you can select the file using a graphical interface.
Finally, the Submit button is added to the screen. Figure 3.4 shows what comes out when you execute the script.
Figure 3.4 A more complex form.If you click on the Submit button, the data inserted into the form will be sent to reaction.php:
<?php echo "field_1: $field_1<br>"; echo "myradio: $myradio<br>"; echo "passwd: $passwd<br>"; echo "filename: $filename<br>"; ?>
The script displays the values on the screen:
field_1: 23 myradio: 2 passwd: a password filename: /home/hs/boot.img
Keep in mind that the values in the listing show what you have inserted into the form. The gist of the example is that the information from every field in the HTML form will be stored in a variable after being submitted to a PHP file.
Sometimes it is necessary to give the user the opportunity to select more than just one value in a list. Therefore HTML offers a simple solution using select and option:
<html> <body> Select: <br><br> <form action="reaction.php" method="POST"> <select name="fruits[]" multiple size=4> <option value="Orange">Orange <option value="Banana">Banana <option value="Apple">Apple <option value="Pineapple">Pineapple <option value="Strawberry">Strawberry <option value="Cherry">Cherry <option value="Coconut">Coconut </select><br><br> <input type="submit" name="submitbutton"> </form> </body> </html>
Now the user can choose some of the fruits presented in the list. Because more than one fruit can be selected, the data structure used by PHP must be an array. In our example this array is called fruits[]. After submitting the content of the form, the array will contain all values the user has selected. To display the content of the array, a simple function can be used:
<?php foreach ($fruits as $var) { echo "$var<br>"; } ?>
The fruits will be listed one after the other.
3.9.3 Passing Parameters to a Script
In many cases it is useful to call a script and pass some parameters to it. Techniques like that are often needed for banners because the person who has paid for the banner wants to know where a click comes from. For that purpose, parameters are passed to a script that contains information on whose Web site contained the banner.
Let's have a look at a very simple script that does nothing except display two variables.
<?php echo "a: $a<br>\n"; echo "b: $b\n"; ?>
The target is to pass parameters to that script via an URL:
http://localhost/test/script.php?a=234&b=197
The script named script.php located in a directory named test on the local Web server is called with the parameter a=237 and b=197. The names of the script and the parameters are separated using a question mark (?). The list of parameters is separated using ampersands (&).
When executing script.php, the result will be displayed by the browser:
a: 234 b: 197
You have already seen that question marks and ampersands are used as delimiters. What happens if you want to pass one of these signs to the script? Does the Web server get confused because it has to find out which symbols are used as delimiters of which ones are parts of a string? The answer is yes. All "special" characters have to be escaped so that the Web server can parse the URL easily. Luckily PHP provides a function called urlencode, which takes care of things like that. Let's write a small script that generates a list of URLs:
<?php echo "<html><body>\n"; $messages[0] = "Pat and Shelley"; $messages[1] = "Pat & Shelley"; $messages[2] = "Pat & Shelley!"; $messages[3] = "Are you sure?"; $messages[4] = "Hans-Jürgen Schönig"; foreach ($messages as $var) { echo '<a href="script.php?a='.urlencode($var). '"> '.$var."</a><br>\n"; } echo '</body></html>'; ?>
After displaying some HTML code, five strings are defined and assigned to an array called $messages. Each of the strings contains certain characters that have to be escaped by PHP.
In the next step, links are generated using urlencode. Let's call PHP from the command line and see what the HTML code generated by the script looks like:
[hs@athlon test]$ php genurl.php X-Powered-By: PHP/4.0.4pl1 Content-type: text/html <html><body> <a href="script.php?a=Pat+and+Shelley"> Pat and Shelley</a><br> <a href="script.php?a=Pat+%26+Shelley"> Pat & Shelley</a><br> <a href="script.php?a=Pat+%26+Shelley%21"> Pat & Shelley!</a><br> <a href="script.php?a=Are+you+sure%3F"> Are you sure?</a><br> <a href="script.php?a=Hans-J%FCrgen+Sch%F6nig"> Hans-Jürgen Schönig</a><br> </body></html>
As you can see, all characters have been escaped. When executing the script using a Web browser, the strings in the array are displayed as links:
Pat and Shelley Pat & Shelley Pat & Shelley! Are you sure? Hans-Jürgen Schönig
If you click on the first link, script.php will be called:
a: Pat and Shelley b:
The text is displayed on the screen. Because no parameters for $b have been passed to the script, the field is empty.
3.9.4 Working with Hidden Fields
Sometimes it is necessary to pass parameters to a script that should not be seen by the user. In HTML it is possible to use hidden fields. The difference between "ordinary" fields and hidden fields is that hidden fields are not displayed by the browser. Therefore parameters can easily be passed from one script to another without giving the user the opportunity to modify the information stored in a hidden field.
Let's assume that you want to write a script that displays the time the previous script has been created:
<?php $curtime = localtime(); $timestr = strftime("%Y %b %d: %T %Z"); echo "timestr: $timestr<br>\n"; echo ' <html> <body> Hello World <form action="reaction.php" method="POST"> <input type="hidden" value="'.$timestr. '" name="gentime"> <input type="submit" name="submitbutton"> </form> </body> </html> '; ?>
The first script generates the current time and stores it in $timestr. Now a form is generated and the value $timestr is used as the default value of the field called gentime. The only two things that are displayed on the screen are the content of $timestr, Hello World, and a button to submit the information. Reaction.php is called when the user hits the button. Let's have a look at reaction.php:
<?php echo "gentime: $gentime"; ?>
The content of $gentime is displayed on the screen:
gentime: 2001 Nov 01: 12:31:57 CET
The previous script has been generated at the time listed in the output of reaction.php. Sometimes it is useful to pass the time when the first HTML was generated to all files because this way it is possible to find out when a user has entered the page.