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?
filter_input_arrayon some data and then recurse to inner arrays.$_POSTandINPUT_POSTare not the same, flattening$_POSTwill not have any effect onINPUT_POST. In the pure sense, I think you would want to leave$_POSTout of it. My suggestion is for you to flatten your HTML form if at all possible, instead of the input source array. Yes, trickery can be done, but at what cost? Processing time? Maintenance? Documentation? Once you get beyond two dimensions, PHP leaves you to your own devices. :) Notice there is no INPUT_FILES.