HTML checkboxes provide the perfect way for a web developer to receive client input when the client's options might be none, one or many. But the PHP code for processing the checkboxes can be confusing at first. What if a checkbox is not checked? Unlike the text-type input controls, the unchecked checkbox is simply absent from the request. This situation makes it necessary for our action script to know in advance
In the code example, script initialization starts at line 10. We set up an associative array of key=>value pairs. This array is our data model. It lets the script produce checkboxes that are generated dynamically, depending on the contents of the array. If you wanted to add, for example, "Graduates" you just add that to the $options
array following the pattern shown in the code snippet. No other changes to either the form or action script would be needed. The new option would appear automatically. If you think creatively about this array you realize that it does not need to be hard-coded. It might come from the results of a data base query.
The "Action" Script
The action script is the next part of this code snippet. It starts on line 20. If the submit button was fired, we examine our array of options (line 25) and if the option was set in the $_POST["choice"]
variable we set the value in $options
. This strategy accomplishes two things for us. First, it adds a measure of security to our application because we do not make any decisions based solely on the contents of the $_POST array. The external data must match our internal data model or else it will be ignored, thus we have reduced the risk of an attack vector in the external data. Second, it lets us remember the status of the checkboxes from one instance of the form to the next.
The action script is completed at line 35. Obviously the action script could have done something a lot more interesting than just report and remember the checkbox selections. For example, it could have used a data base to generate a list of grade-appropriate text books. That part of the action script would happen near line 29.
The "Form" Script
The second part of the form is generated dynamically from the $options
array (lines 57-74). We use the contents of the $options
array to create the input checkbox controls. This design exploits the key=>value pairs of the PHP associative array to remember what was checked in the last submission of the form.
At line 77 we add the submit button and close the form, then we write the HTML string to the browser on the last line of the script.
In PHP action scripts the $_POST variable is always an associative array, and in this example one element of that array, $_POST["choice"]
You can install this script as-is and run it to see the moving parts.
What Just Happened?
<?php // demo/EE_checkbox_demo.php
echo "<pre>" . PHP_EOL;
// DEMONSTRATE HOW TO SUBMIT AND PROCESS CHECKBOXES
// THESE ARE THE NAMES OF THE CHECKBOXES
( 'Freshman' => NULL
, 'Sophomore' => NULL
, 'Junior' => NULL
, 'Senior' => NULL
// IF THE FORM HAS BEEN SUBMITTED
// SHOW THE CHOICES THAT WERE SELECTED
foreach ($options as $opt => $status)
// THIS IS WHERE YOU MIGHT DO THE PROCESSING FOR THE SELECTED CHOICE
$options[$opt] = " checked ";
echo PHP_EOL . $opt;
// THE FIRST PART OF THE HTML DEFINED IN HEREDOC NOTATION
$html = <<<ENDHTML
function toggle(formName, arrayName, YesNo)
for(i=0; i<xbox.length; i++)
if (xbox[i].name.substr(0,arrayName.length) == arrayName) xbox[i].checked=YesNo;
<form method="post" name="checkForm">
<input type="checkbox" onClick="toggle('checkForm', 'choice', this.checked)"> TOGGLE ALL OR SELECT A GRADE:
// THE SECOND PART OF THE HTML CREATED DYNAMICALLY FROM $options
foreach ($options as $opt => $status)
.= '<input' // START THE INPUT CONTROL TAG
. ' name="choice' // ASSIGN THE NAME AS AN ARRAY [choice]
. '[' // USE BRACKET NOTATION
. $opt // THE ARRAY KEY
. ']' // CLOSE THE ARRAY BRACKET NOTATION
. '" ' // CLOSE THE NAME ATTRIBUTE
. ' type="checkbox"' // THE INPUT CONTROL TYPE ATTRIBUTE
. ' value="' // THE VALUE ATTRIBUTE
. $opt // THE NAME OF THE CHOICE
. '" ' // CLOSE THE VALUE ATTRIBUTE
. $status // CHECKED OR NULL
. " /> $opt" // TEXT FOR THE CLIENT TO SEE
// ADD THE END OF THE DOCUMENT
$html .= '<input name="sb" type="submit" value="MAKE SELECTION" />' . PHP_EOL;
$html .= '</form>' . PHP_EOL;
// WRITE THE FORM
What have we accomplished with this script? We have given the client the convenience of a checkbox-enabled web page. We have made it easy to choose "all or nothing" as well as individual choices. We have used a design that does not depend on external input in any unreasonable way (in other words, we accept only known good values in the $_POST array). And we have created a design that is easy to modify or extend to other use cases.
Another Take on Unchecked Checkboxes
A frequent question is, "How do I get a default value for a checkbox?" You can use a combination of form input controls to accomplish this. Create an input control with an attribute of type=hidden and a name attribute that is the same as the name attribute of your checkbox. Place this input control into the HTML form immediately before
the checkbox. The hidden value will be transmitted if the checkbox is not checked. But if the checkbox is checked, its name:value pair will cause it to override the hidden value in the request array. This is not completely secure; you still have to filter / validate / sanitize the external input, but it goes a long way toward solving a common problem.
To Learn More
<?php // demo/unchecked_checkbox.php
// SHOW HOW TO USE HIDDEN INPUT TO APPLY A VALUE TO AN UNCHECKED CHECKBOX
// SHOW THE POST ARRAY, IF ANY
if (!empty($_POST)) print_r($_POST);
// CREATE THE FORM USING HEREDOC NOTATION
$form = <<<ENDFORM
<input type="hidden" name="my_check_box" value="You Did Not Check It" />
<input type="checkbox" name="my_check_box" value="You Checked It" /> TRY CHECKING OR UNCHECKING THIS BOX
<input type="submit" />
Some further reading on PHP and forms is available here:
Although it was not needed in our article here, this function is important when a script sends external input back to the client browser:
The very useful heredoc
notation is described here. It makes templates drop-dead simple in PHP:
Please give us your feedback!
If you found this article helpful, please click the "thumb's up" button below. Doing so lets the E-E community know what is valuable for E-E members and helps provide direction for future articles. If you have questions or comments, please add them. Thanks!