You Should Be Using PHP Filtering Functions, Part 1

I’ve talked about data sanitization in WordPress in previous posts. This is a topic that’s important not only for those of us working to build solutions for others in WordPress, but also for those who are writing code that will directly interact with a database via PHP.

Sure, there are native WordPress functions to make this process easier, but there are also built-in PHP filtering functions to help with this. Namely filter_var and filter_input and these are things that I think are helpful for PHP developers to know.

PHP Filtering Functions, Part 1: Variables

Filtering variables is done by the aptly named filter_var function. The official definition is:

Filters a variable with a specified filter

The PHP Manual

The definition itself might read a little circular especially if you’re just getting started with PHP or with using filtering functions. The important thing to understand in this definition is what a filter actually is.

So if you’re used to working with, say, boolean values, integers, email addresses, and so on (and who isn’t?), then it makes more sense, doesn’t it? That is, if you need to provide some type of validation around those types of values, then this can help.

What’s great is that regardless of what it is you’re filtering, then filter_var is going to return false whenever the filter fails.

Let’s say you want to filter an email address, then you can do something like this:

  • filter_var($emailAddress, FILTER_VALIDATE_EMAIL);

Of course, it’s not without some gotchas. For example, it won’t validate non-Latin domains. More on this momentarily.

Anyway, maybe you want to filter other types of values:

  • filter_var($url, FILTER_VALIDATE_URL)
  • filter_var('1001', FILTER_VALIDATE_INT)

And you can make them more complicated depending on your needs. Say, for example, you need to determine if an IP is public. Then you can use something more elaborate like this:

  • filter_var($ip, FILTER_VALIDATE_IP, FILTER_FLAG_NO_PRIV_RANGE | FILTER_FLAG_NO_RES_RANGE)

The thing is that it’s important to know how filter_var works as well as what filters are available. That’s really where the usefulness of this comes into play. To that end, I highly recommend reading through the validation filters PHP offers.

Finally, remember the note above about non-Latin domains with email addresses? There are a few cases like this with certain features that you’ll need to review what the manual has to say regarding certain URLs, domains, and so on before using them.

In those cases, unfortunately, filter_var may not always work. Instead, regular expressions can be a suitable replacement.

What About Filtering Inputs?

If you’re experienced with also working with variables like $_GET and $_POST then there is another filtering function specifically for that.

And in the next post, I’ll walk through how to best use those in place what so many of us traditionally use.