Search code examples
phpphp-5.3

filter_var_array() multidimensional array


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 ?


Solution

  • 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;
    }