The flaws of using isset() The flaws of using isset()

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

Published on Apr 8, 2009

Tags: PHP

Related Posts

Did you enjoy this article? If you did here are some more articles that I thought you will enjoy as they are very similar to the article that you just finished reading.

Tutorials

Learn how to code in HTML, CSS, JavaScript, Python, Ruby, PHP, Java, C#, SQL, and more.

No matter the programming language you're looking to learn, I've hopefully compiled an incredible set of tutorials for you to learn; whether you are beginner or an expert, there is something for everyone to learn. Each topic I go in-depth and provide many examples throughout. I can't wait for you to dig in and improve your skillset with any of the tutorials below.