The flaws of using isset()
Published on Apr 8, 2009 by Jamie MunroI am starting to really dislike the PHP function isset(). Today, I was working on a registration system in CakePHP and my password validation was not working. If I left the password field blank and clicked submit, it would come back with other errors, but then the password would come back populated with a long string - a hashed version of an empty string!
After some investigation, I discovered that the AuthComponent in CakePHP was doing an isset() check on the username and password fields. If isset() returned true for both, it would hash the password.
After a quick investigation, it was clear that isset() was returning true when my password field was empty! The weird part is, I think this is specific to a PHP version. I'm not 100% positive on this, but at work we develop locally and then commit our work through SVN to our development server. Up until recently we had a versioning difference, yes I know this is a bad idea, and I'm sure I've seen code using isset() work in one instance and not in the other!
I would love if someone would confirm or deny this fact.
Regardless, this is clearly unacceptable. My field is empty, isset() should not be returning true. My solution is to ALWAYS use !empty(). Don't forget the "!" to negate it because empty() returns true when it's empty!
If you read PHP's documentation, there are still a couple of scenarios when using isset() is needed over empty(). The only real scenario that I use it often is that I expect zero (0) as a valid result. Using !empty(0) will return false, where isset(0) will return true.
Conclusion, save yourself the headaches caused by isset() and use empty() or if you are dealing with arrays, array_key_exists().