PHP when to use filter_var instead of php built-in functions

I noticed that you can do a lot with the PHP filter_var function, which can also be executed with another function.

For example, filters FILTER_VALIDATE_REGEXP , FILTER_SANITIZE_ENCODED and many others also have their respective functions in PHP.

When should I use filter_var and when should I use PHP functions? What are the advantages and disadvantages?

+6
source share
3 answers

The advantage of the filter extension is that you have everything in one place.

But you are right, it does not provide many new features. You can 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 usual htmlspecialchars instead of the filter option.

However, there is filter_var_array where one advantage becomes apparent. You can filter many variables for each configuration file. And you can predefine the list of filters to apply all at the same time :

 $_POST = filter_var_array($_POST, array( "text" => FILTER_SANITIZE_ENCODED, "id" => FILTER_VALIDATE_INT, "title" => FILTER_SANITIZE_ENCODED, )); 

I admit that the magic_quotes example is mainly called, but you get the picture. Unification.

+7
source

So far, I have not found a faster (or better) way to remove special characters from a string than using filter_var

 filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH) 

Like many other questions in PHP, there are several ways to accomplish them. filter_var is convenient.

+6
source

I just run the microtime benchmark test 50 times side by side against the preg_match in the if and filter_var_array , checking the exact same reset data, here are the results of the micro session:

 filter_var_array microtime: 0.000834226608276 preg_match microtime: 0.000180006027222 

filter_var_array looks pretty, but 4-8 times slower than preg_match , so if you have a high traffic site and prefer fast code, I would recommend preg_match .

However, if you like good clean code and it doesn't matter how it works, use filter_var_array , which can be more manageable to apply simple filters to many form requests and form inputs.

But you can also achieve this ease by writing the preg_match function for different scenarios, such as email or alphanumeric, but remember the safety of preg_match when writing a regular expression, for example:

http://blog.php-security.org/archives/76-Holes-in-most-preg_match-filters.html

I would like to see the empathy of using memory on both.

Hope this helps

+1
source

Source: https://habr.com/ru/post/903724/


All Articles