Checking to see if a variable is an integer

PHP programming forum. Ask questions or help people concerning PHP code. Don't understand a function? Need help implementing a class? Don't understand a class? Here is where to ask. Remember to do your homework!

Moderator: General Moderators

Post Reply
SidewinderX
Forum Contributor
Posts: 407
Joined: Fri Jul 16, 2004 9:04 pm
Location: NY

Checking to see if a variable is an integer

Post 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?
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post by Weirdan »

ctype_digit()
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post by superdezign »

is_int()

Or typecast it.
User avatar
Weirdan
Moderator
Posts: 5978
Joined: Mon Nov 03, 2003 6:13 pm
Location: Odessa, Ukraine

Post 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)
User avatar
superdezign
DevNet Master
Posts: 4135
Joined: Sat Jan 20, 2007 11:06 pm

Post 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?
User avatar
Benjamin
Site Administrator
Posts: 6935
Joined: Sun May 19, 2002 10:24 pm

Post 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.
Post Reply