You want to make sure that a valid choice was selected from a drop-down menu generated by the HTML <select/> element.
Use an array of values to generate the menu. Then validate the input by checking that the value is in the array. Example 9-10 uses in_array() to do the validation.
Example 9-10. Validating a drop-down menu with in_array()
1 2 3 4 5 6 7 8 9 10 11 12 |
// Generating the menu $choices = array('Eggs','Toast','Coffee'); echo "<select name='food'>\n"; foreach ($choices as $choice) { echo "<option>$choice</option>\n"; } echo "</select>"; // Then, later, validating the menu if (! in_array($_POST['food'], $choices)) { echo "You must select a valid choice."; } |
The menu that Example 9-10 generates is:
1 2 3 4 5 6 7 8 9 10 11 |
<select name='food'> <option>Eggs</option> <option>Toast</option> <option>Coffee</option> </select> <select name='food'> <option>Eggs</option> <option>Toast</option> <option>Coffee</option> </select> |
To work with a menu that sets value attributes on each <option/> element, use array_key_exists() to validate the input, as shown in Example 9-11.
Example 9-11. Validating a drop-down menu with array_key_exists()
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
// Generating the menu $choices = array('eggs' => 'Eggs Benedict', 'toast' => 'Buttered Toast with Jam', 'coffee' => 'Piping Hot Coffee'); echo "<select name='food'>\n"; foreach ($choices as $key => $choice) { echo "<option value='$key'>$choice</option>\n"; } echo "</select>"; // Then, later, validating the menu if (! array_key_exists($_POST['food'], $choices)) { echo "You must select a valid choice."; } |
The menu that Example 9-11 generates is:
1 2 3 4 5 |
<select name='food'> <option value='eggs'>Eggs Benedict</option> <option value='toast'>Buttered Toast with Jam</option> <option value='coffee'>Piping Hot Coffee</option> </select> |
The methods in Examples 9-10 and 9-11 differ in the kinds of menus that they generate.
Example 9-10 has a $choices array with automatic numeric keys and outputs <option/> elements.
Example 9-11 has a $choices array with explicit keys and outputs <option/> elements with value attributes drawn from those keys.
In either case, the validation strategy is the same: make sure that the value submitted for the form element is one of the allowed choices.
For requests submitted by wellbehaved browsers, this validation rule never fails—web browsers generally don’t let you make up your choice for a drop-down menu.
Remember, though, that there’s nothing requiring that requests to your PHP program come from a well-behaved web browser.
They could come from a buggy browser or from a bored 11-year-old with a copy of the HTTP specification in one hand and a command-line telnet client in the other.
Because you always need to be mindful of malicious, hand-crafted HTTP requests, it’s important to validate input even in circumstances where most users will never encounter an error.