PHP filter_var:如何确保用户提供正确的数据类型 - true或false只 [英] PHP filter_var: How to make sure the user provides correct data types - true or false only

查看:134
本文介绍了PHP filter_var:如何确保用户提供正确的数据类型 - true或false只的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我要比较两个数组,一个是默认设置,另一个由用户输入。

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

当我只在默认设置一个布尔值,所以我想确保用户不会使用字符串或数字。例如,特鲁克斯'或'1'是不能接受的。

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.

下面是我的code的样品,

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

但这种code返回真或假的只有即使用户提供正确的数据类型。我怎样才能解决这个问题?

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

推荐答案

好吧,先上去,你需要检查 $配置包含键 $默认。 [Asside:如果 $配置为用户提供的......他们绝不可能用户提供这样的一个对象,也许你的意思 $配置=阵列( 随机=>中特鲁克斯); ..除非用户提供你的意思是一些其他的开发者为用户(不是Web用户))

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

这篇关于PHP filter_var:如何确保用户提供正确的数据类型 - true或false只的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆