Form Variables not Passing Integers

is_int() vs is_numeric()

is_intOne great way to handle security it to make sure that your code is expecting the type of input it needs, rather than what it gets.  For example if you code is expecting a number then you should make sure it receives a number before it starts executing.  This is basically how you avoid things like SQL injection and other types of buggy handling.

As straight forward as that sounds it gets a little more complicated when you start checking your variables for their proper type.

SO when you post a variable from a form, or you get a variable from the URL they are all treated as strings.  You can test this out by grabbing the variable and testing the variable with gettype($variable)

$testVariable = $_GET['test'];
echo gettype($testVariable);

the test above would check the test variable and spit out what type of variable it is.
So if I have a url with the test variable in it like this you’d expect it to be an integer, but it isn’t – it’s a string.

http://www.domain.com/index.php?test=123

So what do you do? You need to know if it is a set of numbers, and you want to make sure that it isn’t grabbing a bunch of malicious code – so how do you do that? The answer is with the is_numeric() function.

Here’s some test code you can try out.

	if(is_numeric($test)) {
		echo "IT'S NUMERIC!!";
	} else {
		echo "IT'S NOT NUMERIC";
	}

echo "
";

      if(is_int($test)) {
		echo "IT'S INT!!!!";
	} else {
		echo "IT'S NOT INT";
	}

If we test $test = “1234” you’ll see that “It’s Numeric” but “It’s Not INT”. This is because it all numbers but it isn’t an integer.

If we test $test = 1234 you’ll see that “It’s Numeric!” and “It’s INT”. This is because the variable is not longer a string, but is actually an integer.

If we test $test = “1234malicous” you’ll see that it’s neither Numeric or an Int.
 

Other Ways to Test if something is a number

$isNum = (int)0 + $x;
In this case we can test if something is a number by adding an interger based Zero. Using (int) you can type cast what ever follows it as an integer – this will return the number or 0. If you get a number back then it is in fact a number, and if you don’t get a number you get 0. So here is some test code

$x = 123;
$isNum = (int)0 + $x;
if ($isNum) {
	echo "$isNum is a Number";
} else {
	echo "$isNum Not a number!";
}

Here is a break down of test variables for this

X = result
123 123 is a Number
“123” 123 is a Number
“123number” 123 is a Number
123number Syntax Error
“number123” 0 Not a number!
“number” 0 Not a number!

The odd ball in this list is that “123number” which is a string gets treated as a number in this scenario. Also “123” which is a string as well is considered a number (which that is fine since every $_POST or $_GET variable would be a string – it is just strange that this test actually strips the following characters after the numbers. This could potentially cause issues.

You may also like...