Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP when to use filter_var instead of built in php functions

Tags:

php

filter-var

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?

like image 438
Tiddo Avatar asked Dec 14 '11 00:12

Tiddo


3 Answers

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.

like image 114
mario Avatar answered Oct 07 '22 12:10

mario


To this day I haven't found a faster (or better) way of removing special characters from a string than using filter_var

filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_STRIP_HIGH)

Like many things in PHP, there are multiple ways of doing them. filter_var is convenient.

like image 25
George P Avatar answered Oct 07 '22 11:10

George P


I just run a microtime benchmark side by side 50 times against preg_match in an if statement and filter_var_array validating the exact same reset data, here are the microtime results:

filter_var_array
microtime: 0.000834226608276

preg_match
microtime: 0.000180006027222

filter_var_array looks pretty but is 4 to 8 times slower than preg_match so if you have a high traffic website and prefer speedy code I would recommend preg_match.

However if you like nice clean code and don't really care how it runs then use filter_var_array which may be more manageable for applying easy filters on many forms requests and inputs.

But this kind of ease can also be achieved by writing a preg_match function for different scenarios such as email or alphanumeric but keep in mind preg_match security when writing the regex for example:

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

I would like to see a memory usage compassion on both also.

Hope this helps

like image 33
Fatal Cleric Avatar answered Oct 07 '22 11:10

Fatal Cleric