I'm working on an API endpoint that takes a POST request of form x-www-form-urlencoded
. This mostly takes your typical set of string values, but in some cases, the values can be an array, which come in as duplicate keys, like so:
name1=foo&name2=bar&arr=value1&arr=value2&arr=value3
I want to end up with the following:
[
'name1' => 'foo',
'name2' => 'bar',
'arr' => [value1, value2, value3]
]
I've tried the following:
filter_input_array(INPUT_POST, [
'name1' => FILTER_SANITIZE_STRING,
'name2' => FILTER_SANITIZE_STRING,
'arr' => [
'filter' => FILTER_DEFAULT,
'flags' => FILTER_FORCE_ARRAY
]
]);
which gives me
(
[name1] => foo
[name2] => bar
[arr] => Array
(
[0] => value3
)
)
and
parse_str(file_get_contents("php://input"), $params);
which gives me:
(
[name1] => foo
[name2] => bar
[arr] => value3
)
In both cases, the duplicate keys are overwritten, and I only get the last value.
The top comment of the parse_str function mentions that it does not parse duplicate keys in the CGI standard way, and presents a hefty function to manually parse out the fields.
I'm wondering if there is a simpler way to do this, I simply want to get a sanitized array of all the input from the x-www-form-urlencoded
POST call.
Ideally just something like
return filter_input_array(INPUT_POST, FILTER_SANITIZE_STRING); // also FILTER_SANITIZE_ARRAY for duplicate keys
Is there any function that can accomplish this basic task, or do I really need to roll my own? If so, what's the best way to blanket sanitize an arbitrary user-input array coming in via this POST method, since I would wind up just using a function similar to that in the linked comment above?