Elijah Woods
Elijah Woods

Reputation: 58

Determine whether a checkbox is checked upon form submission

i have been looking for this script for a while now. I have some rules and then i have a checkbox to click if you agree the terms and rules.

Now how do i make a check in PHP if the person has checked that box and agreed to the rules? Thanks for ur help, i appreciate it!

Upvotes: 0

Views: 10571

Answers (5)

markus
markus

Reputation: 40675

It's totally enough to check for:

$userAgrees = false;

if (isset($_POST['myCheckbox']))
{
   $userAgrees = true;
}

Upvotes: 2

meder omuraliev
meder omuraliev

Reputation: 186562

form.php:

<form action="checkbox-form.php" method="post">
    <label for="formWheelchair">Do you need wheelchair access?</label>
    <input type="checkbox" name="formWheelchair" value="Yes" id="formWheelchair" />
 <input type="submit" name="formSubmit" value="Submit" />
</form>

checkbox-form.php:

if(isset($_POST['formWheelchair']) && 
$_POST['formWheelchair'] == 'Yes') 
{
    $wheelchair = true;
}
else
{
    $wheelchair = false;
}
    var_dump( $wheelchair ); 

// shorthand version:

    $wheelchair = isset($_POST['formWheelchair'])?true:false;

Straight from: http://www.html-form-guide.com/php-form/php-form-checkbox.html

Note: At a later point you may want to use sessions to store the data for server-side validation if the user has not entered in all the fields.

Upvotes: 0

Rob
Rob

Reputation: 48369

Assuming you have a form that looks something like this:

<form method="post" action="some_handler.php">
    <label for="option1">Option 1</label>
        <input id="option1" type="checkbox" name="option1" />
    <label for="option2">Option 2</label>
        <input id="option2" type="checkbox" name="option2" />
    <!-- submit, etc -->
</form>

You can check for the presence of the checkbox values (by name) in $_POST, i.e.

<?php
$optionOne = isset( $_POST['option1'] );
$optionTwo = isset( $_POST['option2'] );

If the boxes aren't checked, $_POST won't contain values for them.

Upvotes: 3

&#211;lafur Waage
&#211;lafur Waage

Reputation: 70001

If the form is a method POST form. Then on the action page you should have access to the $_POST variable.

Check out the results of this on your action page.

echo "<pre>";
print_r($_POST);
echo "</pre>";

The $_POST variable will be an array. You can access the value of the array like this.

if($_POST["key"] == "value")

Where the key is the name in the output above.

Upvotes: 1

code_burgar
code_burgar

Reputation: 12323

In form html:

<input type="checkbox" name="terms">

In php script that the form posts to:

if ( $_POST['terms'] == 'on' ) {

  echo 'User accepted terms';

}

Upvotes: -1

Related Questions