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?
/**
* 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);
}
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments