Basic Form Validation of Integer Input

Discussions of secure PHP coding. Security in software is important, so don't be afraid to ask. And when answering: be anal. Nitpick. No security vulnerability is too small.

Moderator: General Moderators

Post Reply
Kray26
Forum Newbie
Posts: 2
Joined: Sat Jan 22, 2011 3:06 pm

Basic Form Validation of Integer Input

Post by Kray26 »

I'm having some trouble validating an entry to my form. When i enter a valid number such as 3285 i get the first error message ([7]) returned. I can't find anything wrong with my code so if anyone could point me in the right direction it would be appreciated. I have only been doing PHP for 2 weeks so it may be something simple for which i apologise.

Here is my code:

Code: Select all

if ($POST['extension'] != strval(intval($_POST['extension']))) {
		$errors[7] = 'Phone Extension must be a number';
		} else {
			if (($_POST['extension'] < 3000) || ($_POST['extension'] > 3599)) {
				$errors[8] = 'Extension must be between 3000 and 3599';
				}
		}
Here is my unexpected output:

Code: Select all


Phone Extension must be a number

User avatar
social_experiment
DevNet Master
Posts: 2793
Joined: Sun Feb 15, 2009 11:08 am
Location: .za

Re: Basic Form Validation of Integer Input

Post by social_experiment »

Form input is always string so you are passing a string value to intval, which returns 0 (or false). Try using is_numeric() to test if a value from a form is numeric.

Code: Select all

<?php
if (!is_numeric($_POST['extension'])) {
                $errors[7] = 'Phone Extension must be a number';
                } else {
                        if (($_POST['extension'] < 3000) || ($_POST['extension'] > 3599)) {
                                $errors[8] = 'Extension must be between 3000 and 3599';
                                }
                }
?>
Hth
“Don’t worry if it doesn’t work right. If everything did, you’d be out of a job.” - Mosher’s Law of Software Engineering
Kray26
Forum Newbie
Posts: 2
Joined: Sat Jan 22, 2011 3:06 pm

Re: Basic Form Validation of Integer Input

Post by Kray26 »

Thank you social_experiment the is_numeric function works perfectly. Also thank you for the info about form input always being string this should help me out in the future.

Kray
User avatar
Technocrat
Forum Contributor
Posts: 127
Joined: Thu Oct 20, 2005 7:01 pm

Re: Basic Form Validation of Integer Input

Post by Technocrat »

Just as an FYI ctypes are faster. In your case you ctype-digit
User avatar
Jonah Bron
DevNet Master
Posts: 2764
Joined: Thu Mar 15, 2007 6:28 pm
Location: Redding, California

Re: Basic Form Validation of Integer Input

Post by Jonah Bron »

If you don't want to validate it, and just want to force it clean, use intval(). Use instead of mysql_real_escape_string() for integers.

http://php.net/intval
Post Reply