从很久以后回到剧本后,我被困在突然失败的卫生处理中
我在过滤器中发现问题意外返回false
。
以下是复制我意想不到的结果的示例:
$test = [ 'apple', 'bananna', 'orange', 'lime', 'grape', ];
var_export( filter_var( $test, FILTER_UNSAFE_RAW )); // false
我认为FILTER_UNSAFE_RAW
应该只返回输入(在这种情况下是一个数组)不变
我的理解/方法错了吗?
注意:
我的代码必须严格依赖自己,并且尽可能轻量级,所以我只是在需要时编写简单的辅助函数,而不是加载第三方库/类。
示例:
$filters = [
'sanitize' => [
'foo' => FILTER_SANITIZE_EMAIL,
'bar' => FILTER_UNSAFE_RAW,
],
'validate' => [
'foo' => FILTER_VALIDATE_EMAIL,
'bar' => [
'filter' => FILTER_VALIDATE_REGEXP,
'flags' => FILTER_REQUIRE_ARRAY,
'options' => [ 'regexp' => '/(apple|grape)/' ],
],
],
];
$test = [
'malicious' => 'something bad',
'foo' => 'test@ema.il',
'bar' => [ 'apple', 'grape', 'orange', ],
];
// validate
$checked = sanitizeInput( $filters, $test );
// sanitizer
function sanitizeInput( $f, $input )
{
// sanitize
$sanitized = filter_var_array( $input, $f['sanitize'] )
// validate
$validated = filter_var_array( $sanitized, $f['validate'] );
// if anything appears to have failed validation (was set to FALSE)
if( FALSE !== strpos( json_encode($validated), 'false' ))
{
...
如您所见,这种方法要求bar
通过消毒,即使不需要消毒行动。
我是否误解FILTER_UNSAFE_RAW
?
答案 0 :(得分:1)
它返回false,因为filter_var()
无法验证数组。而filter_var_array()
就像为每个主题数组的值运行filter_var()
。您可以尝试将数组用作bar
数组中sanitize
的值,FILTER_UNSAFE_RAW
作为过滤器,FILTER_REQUIRE_ARRAY
作为标记
'sanitize' => [
'foo' => FILTER_SANITIZE_EMAIL,
'bar' => [
'filter' => FILTER_UNSAFE_RAW,
'flags' => FILTER_REQUIRE_ARRAY
],
],
另一件需要注意的事情是,因为你只使用FILTER_UNSAFE_RAW
而没有指定标志,所以它什么都不做。所以不消毒它是一样的。虽然它不适用于您的情况,因为它不会传递给验证。
答案 1 :(得分:1)
看起来您没有为filter_var_array
每当处理数组时,都必须包含标记FILTER_REQUIRE_ARRAY
因此,如果没有国旗,您的回复为false
注意: FILTER_UNSAFE_RAW
可选择剥离或编码特殊字符。这也是默认过滤器。
示例强>
$test['bar'] = array( 'apple', 'bananna', 'orange', 'lime', 'grape' );
$san['bar'] = [
'filter' => FILTER_UNSAFE_RAW,
'flags' => FILTER_REQUIRE_ARRAY
];
print_r(filter_var_array( $test, $san ));
<强>输出强>
Array
(
[bar] => Array
(
[0] => apple
[1] => bananna
[2] => orange
[3] => lime
[4] => grape
)
)
编辑工作代码
$filters = [
'sanitize' => [
'foo' => FILTER_SANITIZE_EMAIL,
'bar' => [
'filter' => FILTER_UNSAFE_RAW,
'flags' => FILTER_REQUIRE_ARRAY
],
],
'validate' => [
'foo' => FILTER_VALIDATE_EMAIL,
'bar' => [
'filter' => FILTER_VALIDATE_REGEXP,
'flags' => FILTER_REQUIRE_ARRAY,
'options' => [ 'regexp' => '/(apple|grape)/' ],
],
],
];
$test = [
'malicious' => 'something bad',
'foo' => 'test@ema.il',
'bar' => [ 'apple', 'grape', 'orange', ],
];
// validate
$checked = sanitizeInput( $filters, $test );
// sanitizer
function sanitizeInput( $f, $input ) {
// sanitize
$sanitized = filter_var_array( $input, $f['sanitize'] );
print_r($sanitized);
// validate
$validated = filter_var_array( $sanitized, $f['validate'] );
// if anything appears to have failed validation (was set to FALSE)
if( FALSE !== strpos( json_encode($validated), 'false' )) {}
return $validated;
}