PHP Security - (int) vs FILTER_VALIDATE_INT
The difference is that a cast to int
will always get you an int
, which may or may not be the original value. E.g. (int)'foobar'
results in the int
0
. This makes it safe for most SQL purposes, but has nothing to do with the original value, and you won't even know it.
filter_var
with FILTER_VALIDATE_INT
tells you whether the value is an int
, based on which you can make the decision to use it in an SQL query or display an error message to the user.
Adil
Updated on June 23, 2022Comments
-
Adil almost 2 years
I recently was told there is FILTER_VALIDATE_INT which is great by the way.
My question is in terms of taking an integer value from the website whether it maybe from user or generated from the web application, and passed via query string.
The value (integer) may be displayed or used in mysql query.
I am trying to structure the best possible security method for this.
With that in mind, is it safe to simply use
$myNum = (int)$_GET['num'];
Or
if (filter_var($_GET['num'], FILTER_VALIDATE_INT)) $myNum = $_GET['num'];
Also, please explain what is the difference between using
(int)
andFILTER_VALIDATE_INT
-
Russell Dias over 13 years@deceze would you happen to know if there is much of a difference between
filter_var
and itsis_int
counterpart? -
zerkms over 13 years@Russell Dias: results for
'42'
at least (integer represented as string). -
Russell Dias over 13 years@zerkms Oops didn't realize it tests a numeric string too. Thanks for the example ;)
-
Adil over 13 yearsGot it. It makes sense now. Thanks!
-
Anthony Rutledge over 7 years@deceze It appears that FILTER_VALIDATE_INT also works with strings submitted from forms, so it works a little bit differently than you described.
-
Gromski over 7 years@AnthonyRutledge Yes, of course it operates on strings, that's the entire point. If I had an actual
int
I'd test it withis_int()
and would be sure about the kinds of values it can contain. -
Anthony Rutledge over 7 years@deceze You are wise and now you have proven it, too! ;-)
-
xamoxer1 about 6 yearsits worth the notice that
FILTER_VALIDATE_INT
produces unexpected results for floating point numbers eg3.0
and booleans egtrue
. TEST