Question

Which if the folowing lines is better to use for making sure my code is more secure. Should I be using the settype function of the filter_var functions?

settype($number,'integer') 

or

filter_var($number, FILTER_SANITIZE_NUMBER_INT);

Thanking You

Was it helpful?

Solution

As the documentation says about FILTER_SANITIZE_NUMBER_INT:

Remove all characters except digits, plus and minus sign.

So if you are expecting for instance, an ID to be used in a SQL query, I would go with a regular expression to check that I only have digits /^[0-9]+$/. Because FILTER_SANITIZE_NUMBER_INT would allow -12 which would not make sense in this context.

The main difference between filter_var and settype is that one will parse the variable as a string, and return a string, and the other will cast it to an integer.

$string = "+12";
var_dump(filter_var($string, FILTER_SANITIZE_NUMBER_INT));
settype($string, "integer");
var_dump($string);

Output:

string(3) "+12"
int(12)

So it really depends on the context.

OTHER TIPS

settype and (int) are better than filter_var. Because filter_var have many logic judgements.

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top