Home > PHP/MySQL, Web Development > Use is_numeric() When Testing Form Data!!!

Use is_numeric() When Testing Form Data!!!

by Sam on June 27, 2009 · 4 comments

in PHP/MySQL, Web Development

I just spent the last 2 hours trying to figure out why my input validation class wasn’t working. The scenario was pretty simple; ensure that a particular field was a three digit number. I have been using is_int() for the past two hours and wondering why I haven’t been getting the results I was expecting. Lo and behold, upon consulting the PHP manual in a nice big highlighted box it clearly states that when validating form input one should use the is_numeric() function instead as all form data are retrieved as strings. I am tired, hungry, miserable and feel like an idiot. Still love PHP though. Goodbye two hours…

Short URL for this post:

http://bit.ly/8W4ar

Comments Map

Location data courtesy of GeoSmart

{ 4 comments… read them below or add one }

1 Bosnia and Herzegovina d00de from Federation of Bosnia and Herzegovina, Bosnia and Herzegovina August 4, 2009 at 2:19 am

You should really use a debugger…

2 Jamaica Sam from Manchester, Jamaica August 4, 2009 at 12:04 pm

Twitter: @SamuelFolkes

Good point. Had I done so it would have saved me a LOT of time.

3 Netherlands Willem from Groningen, Netherlands August 6, 2009 at 2:27 am

Remember that is_numeric() also accepts strings such as “10e2″ als valid numeric values. Try ctype_digit() to check if a string contains only digits. ctype_digit() also returns true on empty strings (since they do not contain anything else than digits) so you will have to check for that as well (test using $string === ”).

4 United States Restless from Missouri, United States October 10, 2009 at 10:45 am

I like using type casting too.
IE:
$number = (int) $_GET['number'];

If it’s not a pure digit number submitted, it makes $number blank.

Leave a Comment

You can use these HTML tags and attributes: <a href="" title=""> <abbr title=""> <acronym title=""> <b> <blockquote cite=""> <cite> <code> <del datetime=""> <em> <i> <q cite=""> <strike> <strong> <pre lang="" line="" escaped="">

Previous post:

Next post: