php filter var returning a wrong result

假如想象 提交于 2019-12-10 18:26:05

问题


I wanted to use the php filer_var function but it's returning a wrong result, it seems that it doesn't take into account the range:

$v = 54;

$int_opts = array (

    'min_range' => 0,
    'max_range' => 24

);

if ( filter_var($v, FILTER_VALIDATE_INT, $int_opts) ) echo 'an integer';

else echo 'not an integer';

This shouldn't be an integer as 54 is not between 0 and 24, but it returns true and echoes "an integer".

What's the problem here?

Thanks.


回答1:


The "options" array needs to have a member named "options". From the manual:

$options = array(
    'options' => array(
        'default' => 3, // value to return if the filter fails
        // other options here
        'min_range' => 0
    ),
    'flags' => FILTER_FLAG_ALLOW_OCTAL,
);

you're not passing that so the behaviour displayed is okay.




回答2:


$options = array(); 
$options['options']['min_range'] = 0; 
$options['options']['max_range'] = 24; 
$options['flags'] = FILTER_FLAG_ALLOW_OCTAL; 
var_dump(filter_var(54, FILTER_VALIDATE_INT, $options)); //bool(false)
var_dump(filter_var(21, FILTER_VALIDATE_INT, $options)); //int(21)

It works this way.

About FILTER_FLAG_ALLOW_OCTAL:

Regards inputs starting with a zero (0) as octal numbers. This only allows the succeeding digits to be 0-7. According to this:

var_dump(filter_var(06, FILTER_VALIDATE_INT, $options)); //int(6)
var_dump(filter_var(09, FILTER_VALIDATE_INT, $options)); //int(0)



回答3:


Version 5.3.8 purports to have fixed bug #47745 which meant that FILTER_VALIDATE_INT wasn't allowing a minimum integer.

The file you might want to check is ext/filter/logical_filters.c

void php_filter_int(PHP_INPUT_FILTER_PARAM_DECL) /* {{{ */
{
....


来源:https://stackoverflow.com/questions/7267060/php-filter-var-returning-a-wrong-result

标签
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!