You want to make sure only valid checkboxes are checked.
For a single checkbox, ensure that if a value is supplied, it’s the correct one. If a value isn’t supplied for the checkbox, then the box wasn’t checked.
Example 9-13 figures out whether a checkbox was checked, unchecked, or had an invalid value submitted.
Example 9-13. Validating a single checkbox
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 |
// Generating the checkbox $value = 'yes'; echo "<input type='checkbox' name='subscribe' value='yes'/> Subscribe?"; // Then, later, validating the checkbox if (filter_has_var(INPUT_POST, 'subscribe')) { // A value was submitted and it's the right one if ($_POST['subscribe'] == $value) { $subscribed = true; } else { // A value was submitted and it's the wrong one $subscribed = false; print 'Invalid checkbox value submitted.'; } } else { // No value was submitted $subscribed = false; } if ($subscribed) { print 'You are subscribed.'; } else { print 'You are not subscribed'; } |
For a group of checkboxes, use an array of values to generate the checkboxes. Then, use array_intersect() to ensure that the set of submitted values is contained within the set of acceptable values, as shown in Example 9-14.
Example 9-14. Validating a group of checkboxes
1 2 3 4 5 6 7 8 9 10 11 12 |
// Generating the checkboxes $choices = array('eggs' => 'Eggs Benedict', 'toast' => 'Buttered Toast with Jam', 'coffee' => 'Piping Hot Coffee'); foreach ($choices as $key => $choice) { echo "<input type='checkbox' name='food[]' value='$key'/> $choice \n"; } // Then, later, validating the radio button submission if (array_intersect($_POST['food'], array_keys($choices)) != $_POST['food']) { echo "You must select only valid choices."; } |
For PHP to handle multiple checkbox values properly, the checkboxes’ name attribute must end with [], as described in Recipe 9.17.
Those multiple values are formatted in $_POST as an array. Since the checkbox name in Example 9-14 is food[],
$_POST[‘food’] holds the array of values from the checked boxes.
The array_intersect() function finds all of the elements in $_POST[‘food’] that are also in array_keys($choices).
That is, it filters the submitted choices ($_POST[‘food’]), only allowing through values that are acceptable—keys in the $choices array.
If all of the values in $_POST[‘food’] are acceptable, then the result of array_intersect($_POST[‘food’], array_keys($choices)) is an unmodified copy of $_POST[‘food’]. So if the result isn’t equal to $_POST[‘food’], something invalid was submitted.