PHP input filtering for complex arrays

前端 未结 1 852
闹比i
闹比i 2020-12-15 12:22

Official PHP documentation states that filter_var_array() supports array filtering in the following format:

$data = array(
    \'testarray\'             


        
相关标签:
1条回答
  • 2020-12-15 13:00

    Idea 1

    Consider using FILTER_CALLBACK. In this way, you can write a callback function that itself uses the filter extension, thus providing a recursive ability.

    function validate_array($args) {
        return function ($data) use ($args) {
            return filter_input_array($data, $args);
        };
    }
    

    This will generate the callback functions.

    $args = array(
        'user' => array(
            'filter' => FILTER_CALLBACK,
            'options' => validate_array(array(
                'age' => array('filter' => FILTER_INPUT_INT),
                'email' => array('filter' => FILTER_INPUT_EMAIL)
            ))
        )
    );
    

    This is what the config array would then look like.

    Idea 2

    Do not hesitate to pat me on the back for this one because I am quite proud of it.

    Take an arg array that looks like this. Slashes indicate depth.

    $args = array(
        'user/age' => array('filter' => FILTER_INPUT_INT),
        'user/email' => array('filter' => FILTER_INPUT_EMAIL),
        'user/parent/age' => array('filter' => FILTER_INPUT_INT),
        'foo' => array('filter' => FILTER_INPUT_INT)
    );
    

    Assume your data looks something like this.

    $data = array(
        'user' => array(
            'age' => 15,
            'email' => 'foo@gmail.com',
            'parent' => array(
                'age' => 38
            )
        ),
        'foo' => 5
    );
    

    Then, you can generate an array of references that map keys such as 'user/age' to $data['user']['age']. In final production, you get something like this:

    function my_filter_array($data, $args) {
        $ref_map = array();
        foreach ($args as $key => $a) {
            $parts = explode('/', $key);
            $ref =& $data;
            foreach ($parts as $p) $ref =& $ref[$p];
            $ref_map[$key] =& $ref;
        }
        return filter_var_array($ref_map, $args);
    }
    
    var_dump(my_filter_array($data, $args));
    

    Now the only question is how you deal with the mismatch between the validation record and the original data set. This I cannot answer without knowing how you need to use them.

    0 讨论(0)
提交回复
热议问题