Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP validation booleans using filter_var

I'm using filter_var to validate boolean values but I did not expect it to not recognize FALSE. Why does this happen?

filter_var(FALSE, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)

returns

null

like image 602
RS7 Avatar asked Feb 03 '12 16:02

RS7


People also ask

How validate boolean in PHP?

The FILTER_VALIDATE_BOOLEAN filter validates value as a boolean option. Possible return values: Returns TRUE for "1", "true", "on" and "yes" Returns FALSE for "0", "false", "off" and "no"

What is Filter_var function in PHP?

PHP | filter_var() Function The filter_var() function filters a variable with the specified filter. This function is used to both validate and sanitize the data. Syntax :- filter_var(var, filtername, options)

What is FILTER_ VALIDATE_ email in PHP?

Definition and Usage. The FILTER_VALIDATE_EMAIL filter validates an e-mail address.


2 Answers

filter_var is new as of PHP 5.2. You've run into a known bug: https://bugs.php.net/bug.php?id=49510 Feel free to vote on or comment on that bug.

You're trying to do something like this:

$v = filter_var($v, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)

There are a number of cheap workarounds like this:

$v = $v===FALSE ? FALSE : filter_var($v, FILTER_VALIDATE_BOOLEAN, FILTER_NULL_ON_FAILURE)
like image 85
dkamins Avatar answered Nov 12 '22 06:11

dkamins


It sounds like this is actually how it's supposed to work, strangely enough (yes, my mind was blown by that). From https://bugs.php.net/bug.php?id=51344

This is going to sound insane when you've looked at the underlying filter code, but this is actually correct according to the documentation: the default behaviour of filter_input() is to return NULL for non-existent inputs and false when validation fails, and FILTER_NULL_ON_FAILURE simply flips that behaviour to false for non-existent inputs and NULL on validation failure. (No, I don't have a clue where that would be useful either, and the name of the flag is unfortunate in the filter_input() context, since it implies that NULL wouldn't normally be returned. It makes more sense when used with filter_var(), which doesn't have the non-existent input case.)

[table omitted due to SO formatting]

I'll pop a comment into the filter_input() and filter_input_array() implementations to note that this is by design, even though the code does kind of look wrong.

Closing Won't Fix.

like image 22
Machavity Avatar answered Nov 12 '22 06:11

Machavity