4

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.

5
  • Your POST variables doesn't seems to contain any 'additions' values. So why it's not normal that filter_input returns false when you call it ? Commented Mar 7, 2017 at 10:00
  • It does? As I said, the var_dump on $_POST['additions'] clearly returns values. So it does contain additions. Commented Mar 7, 2017 at 10:01
  • Okay, do you want to validate each fields in additions ? Commented Mar 7, 2017 at 10:03
  • 3
    var_dump(filter_input(INPUT_POST, 'additions', FILTER_DEFAULT , FILTER_REQUIRE_ARRAY)); Commented Mar 7, 2017 at 10:05
  • @bxN5 Thanks that worked! Commented Mar 7, 2017 at 10:07

2 Answers 2

5

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.

Sign up to request clarification or add additional context in comments.

Comments

4

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

1 Comment

Thanks for the answer, didn't really think of this. Deserves a cookie. Will accept answer.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.