FILTER_SANITIZE vs FILTER VALIDATE, whats the diff

2019-01-18 16:50发布

问题:

Currently I'm making sort of calculator-like app in PHP with form as method of input. To secure input i'm using filter_input() function. As filter this function take one of elements from two groups: FILTER_SANITIZE and FILTER_VALIDATE, which one should i use to filter input from form?

$number1 = trim(filter_input(INPUT_GET, 'number1', FILTER_VALIDATE_FLOAT));

or

$number1 = trim(filter_input(INPUT_GET, 'number1', FILTER_SANITIZE_FLOAT));

回答1:

It depends on what you need or is suitable for your application, really. One would validate it, and say "Yes, this is (or isn't) a valid float", while the other would clean it for any non-acceptable value and return that, and not say anything if the original input was valid or not to begin with.

The same applies for the other FILTER_SANITIZE_* and FILTER_VALIDATE_*constants, but in this example we'll look at floating-point validation and sanitation, as asked in the original question.

Let's take a look!

$float = 0.032;
$not_float = "0.03b2";

var_dump(filter_var($float, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION));
var_dump(filter_var($not_float, FILTER_SANITIZE_NUMBER_FLOAT, FILTER_FLAG_ALLOW_FRACTION));

var_dump(filter_var($float, FILTER_VALIDATE_FLOAT));
var_dump(filter_var($not_float, FILTER_VALIDATE_FLOAT));

The return from the above dumps would be

string(5) "0.032"  // $float          FILTER_SANITIZE_NUMBER_FLOAT
string(5) "0.032"  // $not_float      FILTER_SANITIZE_NUMBER_FLOAT
float(0.032)       // $float          FILTER_VALIDATE_FLOAT
bool(false)        // $not_float      FILTER_VALIDATE_FLOAT

FILTER_SANITIZE_NUMBER_FLOAT would return a string of the sanitized value (PHP isn't a strongly typed language, so "0.032" == 0.032).
You should also note the FILTER_FLAG_ALLOW_FRACTION flag, which keeps the decimal in place (without that flag it would return 0032).

As you can see, any FILTER_VALIDATE_FLOAT would return a boolean false if it isn't a valid float, and the actual floating value if it was valid (which is a "truthy" value). Keep in mind that 0.00 would be a "falsy" value, so if you wish to check if the validation failed, you should use strict comparison, in case the input was zero, but still valid.

if (filter_var($input, FILTER_VALIDATE_FLOAT) === false) {
    // Oh noes! $input wasn't a valid float!
}

You can see it for yourself in this live demo.

To conclude
If you want to use it in calculations, you might want to validate it, and let the user know that its invalid format, but you could sanitize it, and use it anyway.

Other filters
The examle here shows the usage of FILTER_SANITIZE_FLOAT, but there are other validation and santation filters. See the below links for a full description.

  • List of validation filters
  • List of sanitation filters