使用PHP filter_input_array过滤多维POST [英] Filtering multi-dimensional POST with PHP filter_input_array

查看:59
本文介绍了使用PHP filter_input_array过滤多维POST的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

有没有一种方法可以使用PHP的 filter_input_array 来过滤/清理多维POST数据?

Is there a way to filter/sanitize multi-dimensional POST data with PHP's filter_input_array?

给出了导致以下POST数据的表单:

$_POST[
    'level1a' => [
        'level2a' => [
            'key1' => 'value1',
            'key2' => 'value2'
        ],
        'level2b' => [
            'key1' => 'value1',
            'key2' => 'value2'
        ]
    ],
    'level1b' => [
        'level2a' => [
            'key1' => 'value1',
            'key2' => 'value2'
        ],
        'level2b' => [
            'key1' => 'value1',
            'key2' => 'value2'
        ]
    ]
]

我看不到一种方法来告诉 filter_input_array 函数要检查的数据嵌套更深一层.似乎只有标志 FILTER_REQUIRE_ARRAY ,但是没有办法告诉它需要检查哪个级别.

I don't see a way to tell the filter_input_array function that the data to check is nested one level deeper. There seems to be only the flag FILTER_REQUIRE_ARRAY, but no way to tell on which level it needs to check.

尺寸较小的示例:

如果只是嵌套较少的一组数据,那将非常简单:

If it was just a less nested set of data, it would be pretty simple:

$_POST[
    'level1a' => [
        'level2a' => 'value1',
        'level2b' => 'value2'
    ],
    'level1b' => [
        'level2a' => 'value1',
        'level2b' => 'value2'
    ]
]

可以通过以下方式过滤:

Could be filtered with:

$args = array(
    'level1a' => array(
        'filter' => FILTER_SANITIZE_STRING, 
        'flags' => FILTER_REQUIRE_ARRAY
    ),
    'level1b' => array(
        'filter' => FILTER_SANITIZE_STRING, 
        'flags' => FILTER_REQUIRE_ARRAY
    )
);
$form_data = filter_input_array(INPUT_POST, $args);

但是如何用更多的嵌套数据来解决呢?有没有一种方法可以不拆分/展平POST数据?

But how to solve it with more nested data? Is there a way without splitting/flattening the POST data?

推荐答案

/**
* Trim and filter every value in the nested array
*/
function filter(array &$array)
{
    array_walk_recursive($array, function (&$value) {
         $value = filter_var(trim($value), FILTER_SANITIZE_STRING);
    });

    return $array;
}

/**
* Get filtered POST data
*/
function post(){
  return filter($_POST);
}

这篇关于使用PHP filter_input_array过滤多维POST的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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