20

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) and FILTER_VALIDATE_INT

4
  • To expand on the existing answers, FILTER_SANITIZE_NUMBER_INT is equivalent to (int) casting. Commented Jan 25, 2011 at 3:31
  • 3
    @mario, how can you say that? It is not. Commented May 22, 2013 at 8:20
  • Here is a fun note, FILTER_VALIDATE_INT says '0011' is not an int but '1111' is an int. The more you know... Commented Apr 11, 2018 at 22:32
  • Well (int) is a conversion while filer_var is validation Commented Sep 27, 2022 at 12:22

2 Answers 2

33

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.

Sign up to request clarification or add additional context in comments.

8 Comments

@deceze would you happen to know if there is much of a difference between filter_var and its is_int counterpart?
@Russell Dias: results for '42' at least (integer represented as string).
@zerkms Oops didn't realize it tests a numeric string too. Thanks for the example ;)
Got it. It makes sense now. Thanks!
@deceze It appears that FILTER_VALIDATE_INT also works with strings submitted from forms, so it works a little bit differently than you described.
|
0
 <input type="text" name="param"></input>


$price = filter_input(INPUT_POST, 'param', FILTER_VALIDATE_INT);
if ($price !== false) {
print " a number.";    //works when value is number
}


if(is_int($_POST['param'])){
    print "is number."; //don't works when value is number
}

Please try test with when value is number .

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.