Joshua Bakker
Joshua Bakker

Reputation: 2378

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.

Upvotes: 4

Views: 2918

Answers (2)

tiomno
tiomno

Reputation: 2228

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 :)

Upvotes: 4

Joshua Bakker
Joshua Bakker

Reputation: 2378

Thanks to @bxN5 (PHP filter_require_array is failing):

Changing

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

Into

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

Did the job.

Upvotes: 5

Related Questions