简体   繁体   中英

PHP filter_input validate INT

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

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
}

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');
}

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM