Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP filter_input validate INT

Tags:

php

filter

I have this chunk of code:

$range = array (
    'options' => array (
        'min_range' => 0,
        'max_range' => 10
    )
);

if (!$number = filter_input(INPUT_POST, 'number', FILTER_VALIDATE_INT, $range)) {
    exit ('Error');
}

The "number" input will be sent from a with options from 0 to 10.

the problem is that if number = 0 this returns "Error".

What's wrong with that?

Thanks

like image 870
medk Avatar asked Jun 20 '14 22:06

medk


2 Answers

This is because !0 is true. Why? By adding the ! you are doing a boolean check, so your variable gets converted. And according to the manual:

When converting to boolean, the following values are considered FALSE:

  • the boolean FALSE itself

  • the integer 0 (zero)

  • the float 0.0 (zero)

  • the empty string, and the string "0"

  • ...

So the integer 0 gets converted to false while all other integers are converted to true.

This is why you need to do a type safe check for false or null as these are the values filter_input() returns if it fails for some reason.

$number = filter_input(INPUT_POST, 'number', FILTER_VALIDATE_INT, $range);
if ($number === false) {
    //filter failed
}
if ($number === null) {
    //variable was not set
}
like image 182
kero Avatar answered Sep 29 '22 08:09

kero


I found the solution!

if (
    !$number = filter_input(INPUT_POST, 'number', FILTER_VALIDATE_INT, $range) === 0 
    || !filter_input(INPUT_POST, 'number', FILTER_VALIDATE_INT, $range) === FALSE) 
{
    exit ('Error');
}
like image 29
medk Avatar answered Sep 29 '22 08:09

medk