filter_var_array() multidimensional array

流过昼夜 提交于 2019-12-24 05:35:27

问题


Any ideas why this does not work?

$_POST  = array('edit' => array('name' => 'test'));

die(var_dump(
    filter_var_array($_POST, array(
        'edit["name"]'  => FILTER_SANITIZE_STRING,
        'edit[name]'    => FILTER_SANITIZE_STRING,
    )),
    $_POST
));

How can I sanitize/filter a POST parameter while requiring that it is an array ?


回答1:


Didn't know that filter_var_array() does not support recursion. Don't see no reasons why it shouldn't, though. Here is a simple solution:

// 28 01 2010, Gajus Kuizinas
function hp_path_to_array($keys, $value, $data = array())
{
    if(empty($keys))
    {
        return $value;
    }

    $key        = array_shift($keys);

    $data[$key] = hp_path_to_array($keys, $value, $data);


    return $data;
}

function hp_filter_var_array($data, $rules)
{
    $return = array();

    foreach($rules as $k => $options)
    {
        $path   = explode('[', str_replace(']', '', $k));

        if(empty($path))
        {
            continue;
        }

        if(!is_array($options))
        {
            $filter     = $options;
            $options    = array();
        }
        else
        {
            $filter     = $options['filter'];

            unset($options['filter']);
        }

        $value          = $data;

        foreach($path as $key)
        {
            if(isset($value[$key]))
            {
                $value  = $value[$key];
            }
            else
            {
                $value  = NULL;
                break;
            }
        }

        $return += hp_path_to_array($path, filter_var($value, $filter, $options));

        unset($rules[$k]);
    }

    $return += filter_var_array($data, $rules);

    return $return;
}



回答2:


Trim and sanitize nested arrays

$array = $_POST;

array_walk_recursive($array, function (&$v) {
  $v = filter_var(trim($v), FILTER_SANITIZE_STRING);
});

$prepared = $array;



回答3:


There is a filter flag that does just this: it makes sure that your parameter $_POST['edit'] is an array, and that filters/sanitizes the array's elements instead of the parameter itself.

$_POST  = array('edit' => array('name' => 'test'));

die(var_dump(
    filter_var_array($_POST, array(
        'edit' => [
            'filter' => FILTER_SANITIZE_STRING,
            'flag' => FILTER_REQUIRE_ARRAY
        ]
    ))
));


来源:https://stackoverflow.com/questions/4829355/filter-var-array-multidimensional-array

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