Difference between filter_var and filter_input on input data validation

2k Views Asked by At

What's the difference between using one of these two functions when validating user input? Strictly regarding the function calls, there's no requirement to change the $_POST array for instance.

$result = filter_var($_POST['user_input'], FILTER_VALIDATE_INT);

vs

$result = filter_input(INPUT_POST, 'user_input', FILTER_VALIDATE_INT);

Or there's no difference between the two calls above, not even performance wise, but rather just a matter of preference?

PS: I know there's a similar question on SO - Differences between filter_var and filter_input - but that just states how the 2 methods should be called, not what's the actual difference.

2

There are 2 best solutions below

2
deceze On BEST ANSWER

If the request body does not contain the parameter user_input at all, $_POST['user_input'] will trigger a notice, filter_input(INPUT_POST, 'user_input', ..) won't.

2
RDardelet On

From what i read on php.net,

The filter_var will simply work for any variable in your code, whenever you use it, it will check the value at that moment.

The filter_input value will check the original values of your input, meaning that if you change $_POST['something'], the filter_input(INPUT-POST, "something", FILTER) will perform a check on the value it had before you altered it. It also doesn't seem to trigger a E_NOTICE on execution when the value is not set.

Reference post on php.net