1

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();
}
2
  • 3
    You could indeed just test it, no? Just a remark - the fields will not be marked as empty if they have a space in it. If you want to remove all the spaces, you should use trim. Commented Jun 30, 2013 at 9:35
  • @arbitter Thank you for the TRIM recommendation. Commented Jun 30, 2013 at 9:37

2 Answers 2

2

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!

Sign up to request clarification or add additional context in comments.

2 Comments

Thank you very much for this input! Would I just use the trim() directly in my IF statement or do I need to put the $_POSTs in a STRING/VARIABLE like $lastname = trim($_POST["lastname"]) in order to accomplish my desired result?
Depends on your version of PHP. PHP < 5.5 you'll need to do $lastname = trim($_POST['lastname']; if (empty($lastname)) ... but 5.5 you can do if (empty(trim($_POST['lastname'])))...
0
if ($_POST["firstname"]==""||$_POST["lastname"]==""||$_POST["cellphone"]==""||$_POST["email"]=="")
{
    header("Location: http://www.domain.com/error.php?ec=empty");
    exit();
}

Try this instead

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.