I noticed there are many things you can do with the PHP filter_var
function which can also be done with other function.
For example, the filters FILTER_VALIDATE_REGEXP
, FILTER_SANITIZE_ENCODED
and many more also have their respective dedicated functions in PHP.
When should I use filter_var
and when should I use the PHP functions? What are the advantages and disadvantages?
The advantage of the filter
extension is that you have everything in one place.
But you are right, it doesn't provide much novel features. You could do most of the stuff with existing functions, in particular preg_replace
or preg_match
instead of FILTER_VALIDATE_REGEXP
. Or typecasting, and using the normal htmlspecialchars
instead of the filter option.
There is however filter_var_array
, where one benefit becomes apparent. You can filter loads of variables per config. And you can predefine a list of filters to apply all at once:
$_POST = filter_var_array($_POST, array(
"text" => FILTER_SANITIZE_ENCODED,
"id" => FILTER_VALIDATE_INT,
"title" => FILTER_SANITIZE_ENCODED,
));
I admit that's basically a triggered magic_quotes example, but you get the picture. Unification.