这是检查PHP检查复选框的正确方法吗?

chr*_*ude 1 html php forms checkbox

我有这段代码来检查我的ToS复选框是否已选中:

if (!isset($_POST['tosagree'])) {//if the user did not agree to ToS
    $errors[] = '<span>Please agree to the Terms of Service.<span>';
}
Run Code Online (Sandbox Code Playgroud)

出于某种原因,它允许我在那里注册那些代码.奇怪的是,如果任何其他字段不是字段并且未检查该字段,则它将打印错误,但如果这是唯一的问题,则允许用户注册.

更新:在我的代码中看起来像是一个奇怪的问题.如果您想查看217行代码,请输入以下代码:http://pastebin.com/YkERYpeF

Chr*_*nte 6

是否!isset($_POST['tosagree'])足够取决于浏览器.

为安全起见,请始终设置value复选框的属性.然后,您只需检查该值是否存在:

<input type='checkbox' value='agreed'/>
Run Code Online (Sandbox Code Playgroud)

然后这样做:

if (!isset($_POST['tosagree']) || $_POST['tosagree'] != "agreed" ) {
    $errors[] = '<span>Please agree to the Terms of Service.<span>';
}
Run Code Online (Sandbox Code Playgroud)

此外,当value未明确指定属性时,浏览器通常valueOn在检查时设置为.

编辑

好的,我知道发生了什么.在您的PHP代码中,您有以下块:

if (!isset($_POST['tosagree']) || $_POST['tosagree'] != "agreed") {//if the user did not agree to ToS
    $errors[] = '<span>Please agree to the Terms of Service.<span>';
}
Run Code Online (Sandbox Code Playgroud)

然后你有这条线:

if ($un && $e && $p && $ic) { //if there are no errors
Run Code Online (Sandbox Code Playgroud)

问题是,如果未选中TOS复选框,则没有标记.无法打印错误,因为在if您调用的语句中exit().