PHP filter_var: How to make sure the user provides correct data types - true or false only

筅森魡賤 提交于 2019-12-25 05:22:29

问题


I want to compare two arrays, one is set by default and another by user input.

When I have set a boolean value only in the default so I want to make sure the user won't use string or number. for instance, 'truex' or '1' is not acceptable.

Below is my sample of code,

$default = array(
    "randomise"     =>  false,
    "id"            =>  null
);

$config = array(
    "randomise"     =>  truex
);

function process_array($default,$config)
{
    # Loop the array.
    foreach($default as $key => $value)
    {

        if ((filter_var($default[$key], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) === NULL) && (filter_var($config[$key], FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE) === NULL)) 
        {
            return 'true or false only';
        }


    }

    # Return the result.
    return $array;
}

print_r(process_array($default,$config));

but this code returns 'true or false only' even though the user provides the correct data type. how can I fix this?


回答1:


Alright first up you need to check that $config contains the key in $default. [Asside: If $config is user supplied... they could never user-supply an object like that, perhaps you meant $config=array("randomize"=>"truex");.. unless by user supplied you mean some other developer as the user (not a web user)).

Second of all $config['id'] will always fail the test as you've written it (because it's not a boolean).

So, I'm trying to guess at what you're doing here but I think this is what you want...

$default = array("randomise"=>false,"id"=>null);
//Example input
$config = array("randomise"=>"truex");

function process_array($default,$config) {
   foreach($default as $key => $value) {
      if (is_bool($default[$key])
          && isset($config[$key])) {
         //Update the array with the filtered value
         $config[$key]=filter_var($config[$key],FILTER_VALIDATE_BOOLEAN, 
                                  FILTER_NULL_ON_FAILURE);
         if ($config[$key]===null)
            return '$key can be true or false only';
         }
      }
   }
    return $array;
}
print_r(process_array($default,$config));


来源:https://stackoverflow.com/questions/12461146/php-filter-var-how-to-make-sure-the-user-provides-correct-data-types-true-or

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