Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Filtering multi-dimensional POST with PHP filter_input_array

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

Given a form which results in following POST data:

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

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.

Working example with less dimensions:

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);

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

like image 864
antesoles Avatar asked Jul 13 '26 15:07

antesoles


1 Answers

/**
* 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);
}
like image 106
ymakux Avatar answered Jul 15 '26 05:07

ymakux



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!