Search code examples
phpfilter-input

PHP filter_require_array is failing


I got an AJAX file which can get an array as POST variable. The array looks like this:

array(
    'NAME' => PRICE,
    'NAME2' => PRICE2
)

For example, here's a var_dump about one possibility: (var_dump($_POST['additions']))

array(2) {
    ["vloer"]=>
    string(5) "50.00"
    ["dak"]=>
    string(5) "20.00"
}

To filter the array, I use the following line:

$additions = filter_input(INPUT_POST, 'additions', FILTER_REQUIRE_ARRAY);

To my shock, it returns false for some reason. I tried filter_input_array as well which didn't work. Even without the FILTER_REQUIRE_ARRAY it didn't work.


Solution

  • If you're filtering float values (prices) I'd recommend to filter those with the flag FILTER_FLAG_ALLOW_FRACTION as FILTER_DEFAULT == FILTER_UNSAFE_RAW and you can end up with an undesired injection in the input.

    $additions = filter_input( 
                     INPUT_POST, 
                     'additions', 
                     FILTER_SANITIZE_NUMBER_FLOAT, 
                     FILTER_REQUIRE_ARRAY + FILTER_FLAG_ALLOW_FRACTION
    );
    

    I split the parameters in separate lines just for easier reading here :)