Working With Forms in PHP / Page 3 | WebReference

Working With Forms in PHP / Page 3


[previous] [next]

Working With Forms (con't)

#28: Making Sure a Response Is One of a Set of Given Values

As I told you earlier, you can never assume that the data passed on by a form is safe. Let's look at this simple form item:

How do you ensure that the data you're looking at is really Visa, American Express, or MasterCard? Simple: You store the data in array keys and then look at the array to make sure that there's an exact match. Here's an example:

Hacking the Script

One advantage of this method of data storage is that you can temporarily disable an item by changing its value to false. You can also alter the script slightly to provide both verbose values and data values. For example, you may store American Express cards in your database as amex, but when the name of the card is displayed on the screen you want it to show up as American Express.

In that case, you can use a map to remember what's what by storing the database value as the key in the array and the display name as the value. The following example demonstrates that technique.

NOTE: The previous example is extremely useful information to store in a central configuration file.

#29: Using Multiple Submit Buttons

Occasionally you want a form that does two separate things depending on which button a user clicks—one button updates a post while the other button deletes it. You can put two forms on one page that will send the user to two separate pages, but then you have to worry about inserting redundant information into both forms, not to mention that this would be unbearable to the user.

In HTML, buttons also have values, and you can read those values. Construct your form as follows:

Now, in process.php, access $_POST['action'] to get the button the user clicked.


[previous] [next]

URL: