0
if(empty($_POST['name'])){
header("location:users_adduser.php?fail=1"); //no name specified
}

If I echo $_POST['name'] I can see that it is in fact empty. So what gives? How should I be checking for empty input fields?

4
  • 3
    What does var_dump($_POST) give you? Also, is error reporting turned on and do you get any errors? Commented Nov 16, 2011 at 2:38
  • 1
    zainal.wordpress.com/2006/04/25/8 Commented Nov 16, 2011 at 2:44
  • @Shack We can do better than that: The Definitive Guide To PHP's isset And empty ;o) Commented Nov 16, 2011 at 2:47
  • further to Shackrock's comment, you might want to use trim() around $_POST['name'] to get rid of any white-space...which sounds like a prime culprit in this case. Commented Nov 16, 2011 at 2:50

2 Answers 2

3

Try

if (!isset($_POST['name'])){
header("location:users_adduser.php?fail=1"); //no name specified
}

http://php.net/manual/en/function.isset.php

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

2 Comments

It'd be nice if you could elaborate why !isset is supposedly preferable to empty here.
isset() will return true because $_POST['name'] is in fact set, the problem is that it's value is "".
1

According to the documentation, an empty string should be considered...well, empty. I'd try using var_dump() on $_POST and see what comes back, maybe it's not empty after all.

var_dump($_POST);

For testing purposes, comment out the header() call for now and perhaps just issue a print statement to ensure that it is actually evaluating to true. It could be a header redirect issue rather than a problem with empty().

if(empty($_POST['name'])){
  // header("location:users_adduser.php?fail=1"); //no name specified
  print("POST['name'] IS empty!");
}

3 Comments

$_POST['name'] is set, but it's value is "" (if the text input is left blank). According to the PHP manual (php.net/manual/en/function.empty.php), "" is considered to be empty. But that's not happening... this seems like something that people would want to commonly check when getting input from forms, so there has got to be some easy way to do this.
Hi Danny, what were the var_dump() results? It doesn't make sense for empty() to be behaving this way unless there was more than an empty string...In my experience whenever it has seemed like the language is doing something wrong, it turns out that there's something I've missed.
This was actually a mistake on my part. The header calls were the issue. Header was being changed later on down the page so even though empty() did evaluate to true I had some broken logic later on that set the header to something else.

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.