使用PHP检查复选框的状态(对于t& c)

时间:2013-12-13 16:51:13

标签: php html checkbox logic

我坚持通过PHP获取复选框的状态。我花了两个多小时在谷歌尝试不同的方法,但似乎没有任何工作......

基本上我需要逻辑说“如果没有检查,添加错误”。

我尝试过以下方法:

if(!isset($_POST['terms_and_conditions'])){
    $this->addError("You must agree to our terms and conditions");
}

if(isset($_POST['terms_and_conditions']) && $_POST['terms_and_conditions'] == 'true'){
    $this->addError("You must agree to our terms and conditions");
}

if(!isset($_POST['terms_and_conditions']) && !$_POST['terms_and_conditions'] == 'true'){
    $this->addError("You must agree to our terms and conditions");
}

if($_POST['terms_and_conditions'] == "false"){
    $this->addError("You must agree to our terms and conditions");
}

if($_POST['terms_and_conditions'] == false){
    $this->addError("You must agree to our terms and conditions");
}

以下是复选框的代码:

<div id="field">
    <input type="checkbox" value="false" name="terms_and_conditions" id="terms_and_conditions"/>&nbsp;<label for="terms_and_conditions">By clicking this you agree to this site's <a href="terms_and_conditions.php">Terms and Conditions</a></label>   
</div>
我是傻到某个地方出错了吗?它只会使用此方法输出错误,如果选中了框(需要):

if(isset($_POST['terms_and_conditions'])){
    $this->addError("You must agree to our terms and conditions");
}

但是如果我尝试将其设为负片,即:带有感叹号“!”什么都没显示?

最好的解决方法是什么?

谢谢你的时间!

更新

这是register.php文件:

<?php 
require 'core/init.php';
include_once 'includes/files/overall/header_main.php'; 

$error_array = array();

if(Input::exists()) {

if(Token::check(Input::get('token'))) {
    $validate = new Validate();
    $validation = $validate->check($_POST, array(
        'username' => array(
            'required' => true,
            'min' => 2,
            'max' => 20,
            'unique' => 'users'),
        'password' => array(
            'required' => true,
            'min' => 3),
        'password_again' => array(
            'required' => true,
            'matches' => 'password'),
        'name' => array(
            'required' => false,
            'min' => 2,
            'max' => 50)
    ));

    if($validation->passed()) {
        $user = new User();
        $bcrypt = new Bcrypt();

        try {
            $user->create(array(
                'username'  => Input::get('username'),
                'password'  => $bcrypt->hash(Input::get('password')),
                'name'      => Input::get('name'),
                'joined'    => date('Y-m-d H:i:s'),
                'group'     => 1
            ));

            Session::flash('home', 'You have been registered and can now log in!');
            Redirect::to('index.php');

        } catch(Exception $e) {
            die($e->getMessage());
        }

    } else {
        foreach($validate->errors() as $error) {
            echo $error, '<br>';
        }
    }
}
}
?>

<section id="aside">
<aside class="register">

</aside>
</section>

<section id="main_content">
<h1>Sign Up</h1>
<p class="bigger">Join 1000's of <b>docimes</b> and meet new companions - it's easy!</p>
<?php
    if(!empty($error_array)){
        echo '<ul>';
        foreach($error_array as $error){
            echo '<li>'. $error .'</li>';
        }
        echo '</ul>';
    }
?>
<form action="" method="post">
    <div id="field">
        <label for="name">Name</label>
        <input type="text" name="name" value="<?php echo escape(Input::get('name')); ?>" placeholder="name" />
    </div>

    <div id="field">
        <label for="surname">Surname</label>
        <input type="text" name="surname" value="<?php echo escape(Input::get('surname')); ?>" placeholder="Surname" />
    </div>
    <div id="field">
        <label for="email">Email</label>
        <input type="text" name="email" value="<?php echo escape(Input::get('email')); ?>" placeholder="Email" />
    </div>

    <div id="field">
        <label for="username">Username</label>
        <input type="text" name="username" value="<?php echo escape(Input::get('username')); ?>" placeholder="Username" />
    </div>

    <div id="field">
        <label for="password">Password</label>
        <input type="password" name="password" value="" placeholder="Password" />
    </div>

    <div id="field">
        <label for="password_again">Password again</label>
        <input type="password" name="password_again" value="" placeholder="Password again" />
    </div>

    <input type="hidden" name="token" value="<?php echo Token::generate(); ?>"/>
    <input type="submit" value="Signup" />

    <div id="field">
        <input type="checkbox" value="" name="terms_and_conditions" id="terms_and_conditions"/>&nbsp;<label for="terms_and_conditions">By clicking this you agree to this site's <a href="terms_and_conditions.php">Terms and Conditions</a></label>

    </div>
</form>
</section>

<?php   
include_once 'includes/files/overall/footer_main.php'; 
?>

和validate.php类:

<?php
class Validate {
private $_passed = false,
        $_errors = array(),
        $_db = null;

public function __construct() {
    $this->_db = DB::getInstance();
}

public function check($source, $items = array()) {
    foreach($items as $item => $rules) {
        foreach($rules as $rule => $rule_value) {

            $value = trim($source[$item]);

            if($rule === 'required' && $rule_value === true && empty($value)) {
                $this->addError("{$item} is required.");
            } else if (!empty($value)) {

                switch($rule) {
                    case 'min':
                        if(strlen($value) < $rule_value) {
                            $this->addError("{$item} must be a minimum of {$rule_value} characters.");
                        }
                    break;
                    case 'max':
                        if(strlen($value) > $rule_value) {
                            $this->addError("{$item} must be a maximum of {$rule_value} characters.");
                        }
                    break;
                    case 'matches':
                        if($value != $source[$rule_value]) {
                            $this->addError("{$rule_value} must match {$item}.");
                        }
                    break;
                    case 'unique':
                        $check = $this->_db->get('users', array($item, '=', $value));
                        if($check->count()) {
                            $this->addError("{$item} is already taken.");
                        }
                    break;
                    case 'accepted':
                        if($rule === 'accepted' && $rule_value === true){
                            $this->addError("You must agree to our terms and conditions");
                        }
                    break;
                }

            }

        }
    }

    if(empty($this->_errors)) {
        $this->_passed = true;
    }

    return $this;
}

protected function addError($error) {
    $this->_errors[] = $error;
}

public function passed() {
    return $this->_passed;
}

public function errors() {
    return $this->_errors;
}
}

3 个答案:

答案 0 :(得分:2)

当用户检查时,复选框的值将设置为false。因为在您的HTML中,您有<input type="checkbox" value="false"。如果您希望在用户检查时将值设置为value="true",则需要true

但是,使用当前代码时,如果用户未选中复选框但您说他们没有,则应执行第二个和最后一个错误。你必须仔细检查一下。

答案 1 :(得分:0)

不要测试== true(实际上检查时的默认值是“on”。如果选中该复选框,它将显示isset。

if(!isset($_POST['terms_and_conditions'])){
    $this->addError("You must agree to our terms and conditions");
}

print_r($ _ POST)在发布后显示了什么? 要将复选框默认为关闭,只需将值留空。


<强>更新 From here: VALUE不会影响复选框的选中状态。如果要将复选框默认设置为打开,请使用CHECKED。相反,如果用户选中该复选框,VALUE将设置发送到服务器的值。如果未选中该复选框,则不会向服务器发送任何类型的值(isset() == false)。默认情况下,复选框会发送。

如果您没有获得此值,则以下是代码的完全简化版本,以便您可以看到应该发生的事情。当用户点击该复选框时,帖子将返回$_POST['terms_and_conditions']=='on'然后您可以重新添加代码片段,以查看哪些内容无效。

<h1>Sign Up</h1>
<p class="bigger">Join 1000's of <b>docimes</b> and meet new companions - it's easy!</p>
<?php
var_dump($_POST);
?>
<form action="" method="post">
    <div id="field">
        <label for="name">Name</label>
        <input type="text" name="name" value="<?php echo 'name'; ?>" placeholder="name" />
    </div>

    <div id="field">
        <label for="surname">Surname</label>
        <input type="text" name="surname" value="<?php echo 'surname'; ?>" placeholder="Surname" />
    </div>
    <div id="field">
        <label for="email">Email</label>
        <input type="text" name="email" value="<?php echo 'email'; ?>" placeholder="Email" />
    </div>

    <div id="field">
        <label for="username">Username</label>
        <input type="text" name="username" value="<?php echo 'username'; ?>" placeholder="Username" />
    </div>

    <div id="field">
        <label for="password">Password</label>
        <input type="password" name="password" value="" placeholder="Password" />
    </div>

    <div id="field">
        <label for="password_again">Password again</label>
        <input type="password" name="password_again" value="" placeholder="Password again" />
    </div>

    <input type="hidden" name="token" value="<?php echo 'abc'; ?>"/>
    <input type="submit" value="Signup" />

    <div id="field">
        <input type="checkbox" name="terms_and_conditions" id="terms_and_conditions"/>&nbsp;<label for="terms_and_conditions">By clicking this you agree to this site's <a href="terms_and_conditions.php">Terms and Conditions</a></label>

    </div>
</form>

答案 2 :(得分:0)

永远不要将复选框的值设为TRUE或FALSE。

    <input type="checkbox" value="something" name="terms_and_conditions" >
                          -----------^