php - 这是检查复选框被选中的 PHP 的正确方法吗?

标签 php html 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>';
}

出于某种原因,它允许我使用该代码进行注册。奇怪的是,如果任何其他字段不是字段并且未选中该字段,它将打印错误,但如果这是唯一的问题,它允许用户注册。

更新:我的代码中似乎有一些奇怪的问题。如果您想浏览 217 行代码,这里是所有代码:http://pastebin.com/YkERYpeF

最佳答案

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

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

<input type='checkbox' value='agreed'/>

然后这样做:

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

另外,当没有明确指定value属性时,浏览器通常会在选中时将value设置为On

编辑

好的,我知道发生了什么。在您的 PHP 代码中,您有这个 block :

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>';
}

然后你有这一行:

if ($un && $e && $p && $ic) { //if there are no errors

问题是当未选中 TOS 复选框时,您没有标志。无法打印错误,因为在 if 语句中您调用了 exit()

关于php - 这是检查复选框被选中的 PHP 的正确方法吗?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5207210/

相关文章:

php - 获取类别 ID symfony3

javascript - 动力学拖放

python - Django表单错误: 'QueryDict' object has no attribute 'method' when POST assigned

c# - ASP.NET 动态表单生成和提交

javascript - 如何将表单序列化为对象(具有树结构)?

php - 将多个 POST 数组插入 MySql

php - 将html表格数据与mysql数据(DataTables、jEditable等)绑定(bind)

php - 存储与 Web 应用程序相关的文档(.pdf、.doc 等)

javascript - 单击主题时如何在另一页中显示邮件正文

html - IFrame 不在 IOS Safari 上滚动