Page 1 of 1

Checking to see if a variable is an integer

Posted: Sun Jul 01, 2007 7:27 pm
by SidewinderX
I have a script that accepts a GET variable, and that variable is used to query a database. How can I make it so it will only accept numbers/integers to prevent from an sql injection?

Obviousally

IF(it is a number)
//execute query
ELSE
die()

but how to I make sure it is an integer?

Posted: Sun Jul 01, 2007 7:30 pm
by Weirdan
ctype_digit()

Posted: Sun Jul 01, 2007 7:32 pm
by superdezign
is_int()

Or typecast it.

Posted: Sun Jul 01, 2007 7:34 pm
by Weirdan
superdezign wrote:is_int()
It isn't int, it's a numeric string (see the OP's remark about it being from $_GET)

Posted: Sun Jul 01, 2007 7:37 pm
by superdezign
Weirdan wrote:
superdezign wrote:is_int()
It isn't int, it's a numeric string (see the OP's remark about it being from $_GET)
Then, typecasting would be okay instead?

Posted: Sun Jul 01, 2007 7:48 pm
by Benjamin
All get and post variables are initially strings.

I have seen ctype_digit() return false on the number 8 posted from a form. I have no clue why.

For reliability, I use preg_match.

Code: Select all

$is_num = preg_match('#^[\d]{1,12}|[\d]{1,12}\.[\d]{1,12}$#', $foo) ? true : false;
This will ensure it is a number from 1 to 12 digits long OR a number from 1to 12 digits long followed be a decimal point followed by a number from 1 to 12 digits long.