PHP Checkbox

Summary: in this tutorial, you will learn how to use PHP to process a form with one or more checkboxes.

A quick introduction to the checkbox element

A checkbox allows you to select a single value for submission in a form. To create a checkbox, you use the input element with the type checkbox as follows:

<input type="checkbox" name="checkbox_name" value="checkox_value">Code language: HTML, XML (xml)

A checkbox has two states: checked and unchecked.

If you check the checkbox and submit the form using the POST method, the $_POST associative array will contain an element whose key is checkbox_name and value is checkbox_value.

echo $_POST['checkbox_name']; // 'checkbox_value'Code language: PHP (php)

However, if you uncheck the checkbox and submit the form, the $_POST won’t have any element with key checkbox_name. It means that the following expression returns false:

isset($_POST['checkbox_name'])Code language: PHP (php)

To check if a checkbox is checked, you can also use the filter_has_var() function like this:

if(filter_has_var(INPUT_POST,'checkbox_name')) {
     // ...
}Code language: JavaScript (javascript)

The filter_has_var() function returns true if the checkbox_name exists in the INPUT_POST.

A checkbox has no label. Therefore, you should always use a checkbox with a <label> element like this:

<input type="checkbox" name="agree" id="agree">
<label for="agree">I agree</label>Code language: HTML, XML (xml)

In this example, the value of the for attribute of the <label> element is the same as the value of the id attribute of the checkbox. When you associate a label with a checkbox, you can click the label to check or uncheck the checkbox.

Another way to associate a checkbox with a label is to place the checkbox inside the label like this:

<label>
    <input type="checkbox" name="agree"> I agree
</label>Code language: HTML, XML (xml)

In this case, you don’t need to specify the id for the checkbox and the for attribute for the label.

A simple PHP checkbox example

We’ll create a simple form with one checkbox and a submit button.

First, create the following directory and file structure:

.
├── css
│   └── style.css
├── inc
│   ├── .htaccess
│   ├── get.php
│   └── post.php
└── index.phpCode language: plaintext (plaintext)
FileDirectoryDescription
index.php.Contain the main logic that loads get.php or post.php depending on the HTTP request method
header.phpincContain the header code
footer.phpincContain the footer code
get.phpincContain the code for showing a form with a checkbox when the HTTP request is GET.
post.phpincContain the code for handling POST request
.htaccessincPrevent direct access to the files in the inc directory
style.csscssContain the CSS code

index.php

Second, add the following code to the index.php file:

<?php

require __DIR__ . '/inc/header.php';

$errors = [];

$request_method = $_SERVER['REQUEST_METHOD'];

if ($request_method === 'GET') {
	require __DIR__ . '/inc/get.php';
} elseif ($request_method === 'POST') {
	require __DIR__ . '/inc/post.php';
}

if ($errors) {
	require __DIR__ . '/inc/get.php';
} 

require __DIR__ . '/inc/footer.php';Code language: PHP (php)

The index.php loads the form from the get.php file if the HTTP request method is GET. And it loads the post.php file if the form is submitted.

The $errors variable is used to store error messages.

header.php

Third, place the following code to the header.php file:

<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8" />
    <meta name="viewport" content="width=device-width, initial-scale=1.0" />
    <title>PHP Checkbox</title>
    <link rel="stylesheet" href="css/style.css">
</head>

<body class="center">
    <main>Code language: HTML, XML (xml)

footer.php

Fourth, the footer.php file contains the enclosing tags corresponding to the opening tags from the header.php file:

</main>
</body>

</html>Code language: HTML, XML (xml)

get.php

Fifth, create a form in the get.php file:

<form action="<?php echo htmlspecialchars($_SERVER['PHP_SELF']) ?>" method="post">
    <div>
        <label for="agree"> <input type="checkbox" name="agree" value="yes" id="agree" /> I agree to the <a href="#" title="term of service"> Term of Service</a></label>
        <small class="error"><?php echo $errors['agree'] ?? '' ?>
        </small>
    </div>

    <div>
        <button type="submit">Join Us</button>
    </div>
</form>Code language: PHP (php)

post.php

Sixth, add the following code to the post.php file to sanitize and validate the form data:

<?php

// sanitize the value
$agree = filter_input(INPUT_POST, 'agree', FILTER_SANITIZE_STRING);

// check against the valid value
if ($agree) {
	echo  'Thank you for joining us!';
} else {
	$errors['agree'] = 'To join us, you need to agree to the TOS.';
}
Code language: PHP (php)

Summary

  • Use the isset() or filter_has_var() to check if a checkbox is checked or not.
Did you find this tutorial useful?