Validating Form Input: Checkboxes

You want to make sure only valid checkboxes are checked.

<!DOCTYPE html PUBLIC "-//W3C//DTD XHTML 1.0 Transitional//EN"
"DTD/xhtml1-transitional.dtd">
<html xmlns="http://www.w3.org/1999/xhtml" xml:lang="EN" lang="EN">
<head>
<title>PHP</title>
<meta Name="Author" Content="Hann So">
</head>
<body>
<p>
<?php
$fruits = array('red Apples'=>'Apples', 'green Grapes'=>'Grapes', 'yellow Bananas'=>'Bananas');

function display_form($array) {
echo <<<HTML
<form action = "$_SERVER[PHP_SELF]" method="post">
<input type ='checkbox' name='fruit[]' value='None' />None<br />
HTML;
foreach ($array as $key =>$choice) {
	echo "<input type ='checkbox' name='fruit[]' value='$key' />$choice<br />";
}
echo <<<EOF
</select>
<input type="submit" value="Submit" />
</form>
EOF;
}

// make sure the array exists
if (is_array($_POST['fruit'])) {
    // array_intersect() finds allof the elements in $_POST['fruit']
    // that are also in array_keys($fruits)
	if (array_intersect($_POST['fruit'], array_keys($fruits)) == $_POST['fruit']) {
		foreach ($_POST['fruit'] as $value) {
		echo "Your selection is $value<br />";
		}
	}
	else {
		echo "Select a valid choice.";
		display_form($fruits);
	}
} else {
	display_form($fruits);
}
?>
</p>
</body>
</html>

View the effect


Forms | Introduction | Creating a Form | Superglobals | Processing Form Input | Required Fields | Numbers | Drop-Down Menus | Radio Buttons | Checkboxes | Periods in Their Names | Preventing Cross-Site Scripting | Stripping out Slashes | Redirecting the User | Server Information | Determining Browser Type | Sticky Forms
© 2008: Hann So
email: hso@voyager.deanza.edu