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));
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_*
andFILTER_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!
The return from the above dumps would be
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 return0032
).As you can see, any
FILTER_VALIDATE_FLOAT
would return a booleanfalse
if it isn't a valid float, and the actual floating value if it was valid (which is a "truthy" value). Keep in mind that0.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.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.