Andreas
Andreas

Reputation: 187

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.

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.

if (empty($_POST["firstname"]) || empty($_POST["lastname"]) || empty($_POST["cellphone"]) || empty($_POST["email"]) {
    header("Location: http://www.domain.com/error.php?ec=empty");
    exit();
}

Upvotes: 1

Views: 356

Answers (2)

user2533777
user2533777

Reputation:

if ($_POST["firstname"]==""||$_POST["lastname"]==""||$_POST["cellphone"]==""||$_POST["email"]=="")
{
    header("Location: http://www.domain.com/error.php?ec=empty");
    exit();
}

Try this instead

Upvotes: 0

Dormouse
Dormouse

Reputation: 5198

Empty isn't a particularly good validation tool when used blindly and on it's own.

From the PHP manual page it will return true if:

"" (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().

One other thing to think about in the future is that empty() returns TRUE for 0 or 0.0 which is often undesirable behaviour. 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.

For your specified case, empty() and trim() should suffice but you should be aware of it's behaviour for any future validations!

Upvotes: 2

Related Questions