Working with Forms in php. |
| Overview |
| Until now, all examples in this book have been missing a crucial dimension. You can |
| set variables and arrays, create and call functions, and work with objects. All this is |
| meaningless if users can't reach into a language's environment to offer it |
| information. In this hour, you will look at strategies for acquiring and working with |
| user input. |
| On the World Wide Web, HTML forms are the principal means by which substantial |
| amounts of information can pass from the user to the server. PHP is designed to |
| acquire and work with information submitted via HTML forms. |
| In this hour, you will learn |
| How to get and use environment variables |
| How to access information from form fields |
| How to work with form elements that allow multiple selections |
| How to create a single document that contains both an HTML form and the PHP |
| code that handles its submission |
| How to save state with hidden fields |
| How to redirect the user to a new page |
| How to build HTML forms that upload files and how to write the PHP code to |
| handle them |
| Global and Environment Variables |
| Before you actually build a form and use it to acquire data, you need to make a small |
| detour and look again at global variables. You first met these in Hour 6, "Functions." |
| A global variable is any variable declared at the "top level" of a script |
| — |
| that is, |
| declared outside a function. All functions are made available in a built-in associative |
| array called $GLOBALS. This is useful in Listing 9.1 because we can take a peek at |
| all our script's global variables with a single loop. |
Looping Through the $GLOBALS Array |
| 1: <html> |
| 2: <head> |
| 3: <title>Listing 9.1 Looping through the $GLOBALS array</title> |
| 4: </head> |
| 155 |
| 5: <body> |
| 6: <?php |
| 7: $user1 = "Bob"; |
| 8: $user2 = "Harry"; |
| 9: $user3 = "Mary"; |
| 10: foreach ( $GLOBALS as $key=>$value ) |
| 11: { |
| 12: print "\$GLOBALS[\"$key\"] == $value<br>"; |
| 13: } |
| 14: ?> |
| 15: </body> |
| 16: </html> |
| We declare three variables and then loop through the built-in $GLOBALS associative |
| array, writing both array keys and values to the browser. In the output, we were |
| able to locate the variables we defined, but we saw an awful lot more besides these. |
| PHP automatically defines global variables that describe both the server and client |
| environments. These are known, therefore, as environment variables. According to |
| your system, server, and configuration, the availability of these variables will vary, |
| but they can be immensely useful. Table 9.1 lays out some common environment |
| variables. These can be accessed as part of the $GLOBALS array, or directly. |
| Table 9.1: Environment Variables |
| Variable |
| Contains |
| Example |
| $HTTP_USER_AGENT The name and |
| Mozilla/4.6 |
| version of the |
| (X11;I;Linux2.2.6 -15apmac ppc) |
| client |
| $REMOTE_ADDR The IP address |
| 158.152.55.35 |
| of the client |
| $REQUEST_METHOD Whether the |
| POST |
| request was |
| GET or POST |
| $QUERY_STRING For GET |
| name=matt&address=unknown |
| requests, the |
| encoded data |
| send appended |
| to the URL |
| $REQUEST_URI The full address /matt/php- |
| 156 |
| of the request |
| book/forms/eg9.14.html? |
| including query |
| name=matt |
| string |
| $HTTP_REFERER The address of |
| http://www.test.com/a_page.html |
| the page from |
| which the |
| request was |
| made |
| In addition to environment variables, PHP makes some other global variables |
| available to you. The variable $GLOBALS["PHP_SELF"], for example, gives you the |
| path to the script currently running. On my system this was as follows: |
| /matt/php-book/forms/eg9.1.php |
| This variable can also be directly accessed as the global variable $PHP_SELF. This |
| will be useful in many of the examples in this hour. We will often include the HTML |
| forms we use in the same page as the PHP code that analyzes the content they |
| submit. We can use $PHP_SELF as the string assigned to the HTML FORM element's |
| ACTION argument, saving us the trouble of hard-coding the name of the page. |
| PHP's $GLOBALS array will become useful in other ways as well. |
| A Script to Acquire User Input |
| For now, we'll keep our HTML separate from our PHP code. Listing 9.2 builds a |
| simple HTML form. |
A Simple HTML Form |
| 1: <html> |
| 2: <head> |
| 3: <title>Listing 9.2 A simple HTML form</title> |
| 4: </head> |
| 5: <body> |
| 6: <form action="eg9.3.php" method="GET"> |
| 7: <input type="text" name="user"> |
| 8: <br> |
| 9: <textarea name="address" rows="5" cols="40"> |
| 10: </textarea> |
| 11: <br> |
| 12: <input type="submit" value="hit it!"> |
| 13: </form> |
| 14: </body> |
| 15: </html> |
| We define a form that contains a text field with the name "user", a text area with the |
| name "address", and a submit button. It is beyond the remit of this book to cover |
| HTML in detail. If you find the HTML in these examples hard going, take a look at |
| Sams Teach Yourself HTML in 24 Hours |
| or one of the numerous online HTML |
| tutorials. The FORM element's ACTION argument points to a file called eg9.3.php, |
| which processes the form information. Because we haven't added anything more |
| than a filename to the ACTION argument, the file eg9.3.php should be in the same |
| directory on the server as the document that contains our HTML. |
| Listing 9.3 creates the code that receives our users' input. |
Reading Input from the Form |
| 1: <html> |
| 2: <head> |
| 3: <title>Listing 9.3 Reading input from the form in Listing 9.2</title> |
| 4: </head> |
| 5: <body> |
| 6: <?php |
| 7: print "Welcome <b>$user</b><P>\n\n"; |
| 8: print "Your address is:<P>\n\n<b>$address</b>"; |
| 9: ?> |
| 10: </body> |
| 11: </html> |
| This is the first script in this book that is not designed to be called by hitting a link |
| or typing directly into the browser's location field. We include the code from Listing |
| 9.3 in a file called eg9.3.php. This file is called when a user submits the form defined |
| in Listing 9.2. |
| In the code, we have accessed two variables, $user and $address. It should come as |
| no surprise that these variables contain the values that the user added to the text |
| field named "user" and the text area named "address". Forms in PHP4 really are as |
| simple as that. Any information submitted by a user will be available to you in global |
| variables that will have the same names as those of the form elements on an HTML |
| page. |
| Accessing Input from Multiple SELECT Elements |
| The examples so far enable us to gather information from HTML elements that |
| submit a single value per element name. This leaves us with a problem when |
| SELECT |
| working with |
| elements. These elements make it possible for the user to |
| 158 |
| SELECT |
| choose multiple items. If we name the |
| element with plain name |
| <select name="products" multiple> |
| the script that receives this data will only have access to a single value |
| corresponding to this name. We can change this behavior by renaming any |
| elements of this kind so that its name ends with an empty set of square brackets. |
| We do this in Listing 9.4. |
An HTML Form Including a SELECT Element |
| 1: <html> |
| 2: <head> |
| 3: <title>Listing 9.4 An HTML form including a SELECT element</title> |
| 4: </head> |
| 5: <body> |
| 6: <form action="eg9.5.php" method="POST"> |
| 7: <input type="text" name="user"> |
| 8: <br> |
| 9: <textarea name="address" rows="5" cols="40"> |
| 10: </textarea> |
| 11: <br> |
| 12: <select name="products[]" multiple> |
| 13: <option>Sonic Screwdriver |
| 14: <option>Tricorder |
| 15: <option>ORAC AI |
| 16: <option>HAL 2000 |
| 17: </select> |
| 18: <br> |
| 19: <input type="submit" value="hit it!"> |
| 20: </form> |
| 21: </body> |
| 22: </html> |
| In the script that processes the form input, we now find that input from the |
| "products[]" |
| $products |
| element will be available in an array called |
| . We |
| demonstrate this in Listing 9.5. |
| Listing 9.5: Reading Input from the Form in Listing 9.4 |
| 1: <html> |
| 2: <head> |
| 3: <title>Listing 9.5 Reading input from the form in Listing 9.4</title> |
| 4: </head> |
| |
| 159 |
| 5: <body> |
| 6: <?php |
| 7: print "Welcome <b>$user</b><p>\n\n"; |
| 8: print "Your address is:<p>\n\n<b>$address</b><p>\n\n"; |
| 9: print "Your product choices are:<p>\n\n"; |
| 10: print "<ul>\n\n"; |
| 11: foreach ( $products as $value ) |
| 12: { |
| 13: print "<li>$value<br>\n"; |
| 14: } |
| 15: print "</ul>"; |
| 16: ?> |
| 17: </body> |
| 18: </html> |
| SELECT |
| The |
| element is not the only one that allows for multiple values. By giving |
| a number of check boxes the same name, you can allow a user to choose many |
| values within a single field name. As long as the name you choose ends with empty |
| square brackets, PHP compiles the user input for this field into an array. We can |
| SELECT |
| replace the |
| element in Listing 9.4 with a series of check boxes to achieve |
| exactly the same effect: |
| <input type="checkbox" name="products[]" value="Sonic Screwdriver"> |
| Sonic Screwdriver<br> |
| <input type="checkbox" name="products[]" value="Tricorder">Tricorder<br> |
| <input type="checkbox" name="products[]" value="ORAC AI">ORAC AI<br> |
| <input type="checkbox" name="products[]" value="HAL 2000">HAL 2000<br> |
| Accessing All the Fields from a Form in an Associative |
| Array |
| The techniques you have looked at so far work well, as long as your script knows in |
| advance what fields to expect. You may often want to write code that can adapt to |
| changes in a form or even service more than one form, without worrying itself about |
| the names of specific form fields. The global variables that PHP4 makes available |
| provide the solution to this problem. According to whether or not a submitting form |
| used the GET or POST method, you will have access to one or both of |
| $HTTP_GET_VARS or $HTTP_POST_VARS. These are associative arrays that contain |
| the name/value pairs submitted. Listing 9.6 takes advantage of this to list all the |
| fields submitted from a form via a GET request. |
| |
| |
Reading Input from Any Form Using the $HTTP_GET_VARS |
| Array |
| 1: <html> |
| 2: <head> |
| 3: <title>Listing 9.6 Reading input from any form using the $HTTP_GET_VARS |
| array</title> |
| 4: </head> |
| 5: <body> |
| 6: <?php |
| 7: foreach ( $HTTP_GET_VARS as $key=>$value ) |
| 8: { |
| 9: print "$key == $value<BR>\n"; |
| 10: } |
| 11: ?> |
| 12: </body> |
| 13: </html> |
| This code lists the names and values of all parameters passed to it via a GET |
| transaction. Of course, it's not yet smart enough to deal with parameters that have |
| been set up to resolve to arrays. If we were to amend the HTML form in Listing 9.4 |
| that includes a multiple SELECT element to point to the script in Listing 9.6, we |
| would typically get the following output when the form was submitted: |
| user == Matt Zandstra |
| address == London, England |
| products == Array |
| The products array exists in the $HTTP_GET_VARS[products] array item, but we |
| haven't yet written code to take account of this eventuality. Listing 9.7 tests the |
| data type of each of the elements in $HTTP_GET_VARS and amends the output |
| accordingly. |
Reading Input from Any Form Using the $HTTP _GET_VARS |
| array |
| 1: <html> |
| 2: <head> |
| 3: <title>Listing 9.7 Reading input from any form using the $HTTP_GET_VARS |
| array</title> |
| 4: </head> |
| 5: <body> |
| 6: <?php |
| 7: foreach ( $HTTP_GET_VARS as $key=>$value ) |
| 8: { |
| 9: if ( gettype( $value ) == "array" ) |
| 10: { |
| 11: print "$key == <br>\n"; |
| 12: foreach ( $value as $two_dim_value ) |
| 13: print ".........$two_dim_value<br>"; |
| 14: } |
| 15: else |
| 16: { |
| 17: print "$key == $value<br>\n"; |
| 18: } |
| 19: } |
| 20: ?> |
| 21: </body> |
| 22: </html> |
| As before, we use foreach to loop through the $HTTP_GET_VARS array. We use the |
| gettype() function to ascertain whether each of its values is an array. If the value is |
| itself an array, we create a second foreach statement to loop through it, outputting |
0 comments:
Post a Comment