Feb 3 2009

PHP Filter Functions

Late last year, I bookmarked a post on PHP filter functions. I've been using PHP for about 8 years and I've never heard of them. According to the PHP manual, the "filter extension is enabled by default as of PHP 5.2.0." Beforehand, it was an "experimental PECL extension," which might explain its mystery. If you're stuck with less than PHP 5, you're probably out of luck.

Technical details aside, the filters do what you'd expect: filter data. These filters could potentially replace most regular expression validation. Better yet, they provide a nice way to standardize this type of functionality. The workhorse function of this family is:

filter_var($value, $filter)

You simply pass it a variable and a predefined filter flag (or flags). Common filters provide validation of just about anything can you think of: email address, URL, string, integer, float, et al. The function returns a boolean FALSE if a value doesn't pass the filter.

In addition, the filters can also sanitize values. Those flags include sanitization for strings, quotes, special characters, et al. For starters, think of it as a replacement for cleaning GET/POST data with magic_quotes and/or mysql_real_escape_string.

The function that got me the most interested is the big brother to filter_var:

filter_var_array($data, $defintion)

Pass it an array of values, an array of filter definitions and it will give you back an array of results. With a little work upfront, you could streamline form validation with this function. I've got a validation class that I've been using for the past 2-3 years and I'm ready to rework it completely in favor of these filter functions.

I'll follow up this post with some impressions, once I get my hands dirty. However, I wanted to share this with anyone looking to step up their validation.


Great stuff Robbie, same here, been using PHP for quite a while and was unaware.

Tyler — Feb 4 2009

Always nice to find something that will save you time. Hopefully it will work as advertised.

Robbie — Feb 4 2009