PHP -单个复选框进行验证,但即使选中,也不会提交


PHP - Single checkbox validates but even when checked, won't submit.

我在PHP中编写表单验证代码,但我有一个复选框验证的问题。在检查表单时,如果没有选中复选框,它将给出正确的错误消息。

然而,即使你勾选了复选框,它仍然给出相同的错误信息。

下面是到目前为止的代码:
if (isset($_POST['firstname'], $_POST['lastname'], $_POST['address'], $_POST['email'], $_POST['password'])) {
    $errors = array(); 
    $firstname = $_POST['firstname'];
    $lastname = $_POST['lastname'];
    $address = $_POST['address'];
    $email = $_POST['email']; 
    $password = $_POST['password'];
    if (empty($firstname)) {
        $errors[] = 'First name can''t be empty'; 
    }
    if (empty($lastname)) {
        $errors[] = 'Last name can''t be empty'; 
    }
    if (empty($address)) {
        $errors[] = 'Address can''t be empty';
    }
    if (filter_var($email, FILTER_VALIDATE_EMAIL) === FALSE) {
        $errors[] = 'Please enter a valid email'; 
    }
    if (empty($password)) {
        $errors[] = 'Password can''t be empty'; 
    }
}
if (!isset($checkbox)) {
        $errors[] = 'Please agree to the privacy policy';
} 
$sex = $_POST['sex'];
$age = $_POST['age'];
$checkbox = $_POST['checkbox'];
$_SESSION['validerrors'] = $errors;
$_SESSION['firstname'] = $firstname;
$_SESSION['lastname'] = $lastname;
$_SESSION['address'] = $address;
$_SESSION['email'] = $email;
$_SESSION['sex'] = $sex;
$_SESSION['age'] = $age; 
$_SESSION['password'] = $password;
$_SESSION['checkbox'] = $checkbox;
if (!empty($errors)) {
    header('Location: index.php'); 
} else { 
    header('Location: writevalues.php'); 
}

上面代码中的其他一切都很好,但我还没有找到任何对复选框验证情况有帮助的答案。提前感谢!

你正在调用这个代码:

if (!isset($checkbox)) {
        $errors[] = 'Please agree to the privacy policy';
} 

行前:

$checkbox = $_POST['checkbox'];

那么isset($checkbox)当然会返回false因为它在那一点上没有设置!

你可以把if语句改成:

if(!isset($_POST['checkbox'])){ ...
或者将$checkbox = $_POST['checkbox'];行移到if语句上方。