POST Variable Array and filter_input

PhpArraysVariablesPostInput

Php Problem Overview


While using filter_input, I'm not able to pull in a POST array variable. The POST input:

type              => 'container',
action            => 'edit',
data[display]     => 1,
data[query_limit] => 100

I can access the data variable from the $_POST superglobal correctly as an array, but the filter_input function returns nothing:

$data   = $_POST['data']; // Working, woot
$data   = filter_input(INPUT_POST, 'data'); // returns null, should return array
$action = filter_input(INPUT_POST, 'action'); // returns "edit" (correctly)

Is it not possible to use filter_input for a POST array variable?

Php Solutions


Solution 1 - Php

Try :

$data   = filter_input(INPUT_POST, 'data', FILTER_DEFAULT, FILTER_REQUIRE_ARRAY);

Links:

http://php.net/manual/en/function.filter-input.php

http://php.net/manual/en/filter.filters.flags.php

Solution 2 - Php

FILTER_REQUIRE_ARRAY will return false if the POST variable contains a scalar value. If you're unsure or just intend on the POST variable accepting both scalar and array values, use FILTER_FORCE_ARRAY instead, which will treat any input as an array, essentially casting scalar values accordingly.

$data = filter_input(INPUT_POST, 'data', FILTER_DEFAULT, FILTER_FORCE_ARRAY);

Solution 3 - Php

I have used FormData in javascript and post the fields with jquery ajax. The way I receive all these field is:

$arrFields = array('field1','field2','field2','field3', 'field4','field5');
foreach($arrFields as $field){
   $params[$field] = filter_input(INPUT_POST, $field, FILTER_DEFAULT);
}
var_dump($params);

Then I will get all the data into an array which I can pass on...

Solution 4 - Php

Alternatively you can do your filtering in one shot...for example

$MY_INPUT = filter_input_array(INPUT_POST, [
    "item_id" => FILTER_SANITIZE_NUMBER_INT,
    "item_string_code" => FILTER_SANITIZE_STRING,
    "method" => FILTER_SANITIZE_STRING,
    "item_id_array" => array(
        'filter' => FILTER_SANITIZE_NUMBER_INT,
        'flags' => FILTER_REQUIRE_ARRAY
    )
]);

The result is almost the same as the post data in terms of what you get back except instead of the global $_POST being your variable it will be $MY_INPUT in this case.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionjterryView Question on Stackoverflow
Solution 1 - PhpjbrtrndView Answer on Stackoverflow
Solution 2 - PhpreformedView Answer on Stackoverflow
Solution 3 - PhpJørgen Rudolph LåkerView Answer on Stackoverflow
Solution 4 - PhpGoddardView Answer on Stackoverflow