[英]PHP test if POST is empty from FORM fields
I've a FORM that is filled out by a user/visitor on the webpage. 我有一个表单,由用户/访客在网页上填写。 I've added JavaScript to secure as much as possible, but really want to check even on the PHP side that there is DATA in the $_POSTs. 我添加了JavaScript以确保尽可能的安全,但是我真的想甚至在PHP方面检查$ _POSTs中是否有数据。
Is the below CODE correct? 以下代码正确吗? I want to accomplish that NONE of the POSTed fields are EMPTY, meaning that the fields in the FORM was submitted as BLANK. 我想完成,没有一个POSTED字段是EMPTY,这意味着FORM中的字段被提交为BLANK。
if (empty($_POST["firstname"]) || empty($_POST["lastname"]) || empty($_POST["cellphone"]) || empty($_POST["email"]) {
header("Location: http://www.domain.com/error.php?ec=empty");
exit();
}
Empty isn't a particularly good validation tool when used blindly and on it's own. 盲目地单独使用Empty不是一个特别好的验证工具。
From the PHP manual page it will return true if: 在PHP手册页中,如果满足以下条件,它将返回true:
"" (an empty string) 0 (0 as an integer) 0.0 (0 as a float) "0" (0 as a string) NULL FALSE array() (an empty array) $var; (a variable declared, but without a value)
Regarding the variables that you've used the likely values would pass as expected but I could just put some whitespace (" ") in the form fields and have it pass. 关于您使用的可能值的变量将按预期方式通过, 但是我可以在表单字段中放置一些空格(“”)并使其通过。 You will want to trim($_POST["lastname"])
and others before you check it against empty()
. 在对empty()
检查之前,您将需要trim($_POST["lastname"])
和其他。
One other thing to think about in the future is that empty()
returns TRUE for 0 or 0.0 which is often undesirable behaviour. 将来需要考虑的另一件事是, empty()
对于0或0.0返回TRUE,这通常是不受欢迎的行为。 For example if your form asked me the age of my children and one of them was only recently born, I would put in 0
and empty()
wouldn't accept it. 例如,如果您的表格询问我孩子的年龄,并且其中一个孩子刚出生,我将输入0
, empty()
将不接受。
For your specified case, empty()
and trim()
should suffice but you should be aware of it's behaviour for any future validations! 对于您指定的情况, empty()
和trim()
应该足够,但是您应该知道它在以后的任何验证中的行为!
if ($_POST["firstname"]==""||$_POST["lastname"]==""||$_POST["cellphone"]==""||$_POST["email"]=="")
{
header("Location: http://www.domain.com/error.php?ec=empty");
exit();
}
Try this instead 试试这个
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.