Brain Goo

Carpe Crap ’em

Brain Goo header image 2

 

 

HOW TO Use Multiple Filter Flags in PHP Filter Functions

January 9th, 2014 · 2 Comments

Using multiple filter flags in PHP is easy, but the documentation does not explain it well.

The Filter capabilities in PHP 5.3 and above are very powerful and save a ton of effort, but the passing of flags to various filter functions is described minimally as a “bitwise disjunction of flags”. This means you need to pass a bitwise conjunction of flags.

Here’s the english translation:
Pass a pipe-separated list of flags.

That’s it. You need to use the logical ‘OR’ to create a parameter the parser will understand.

If you want to use filter_var() to sanitize $string with FILTER_SANITIZE_STRING and pass in FILTER_FLAG_STRIP_HIGH and FILTER_FLAG_STRIP_LOW, just call it like this:

$string = filter_var($string, FILTER_SANITIZE_STRING, FILTER_FLAG_NO_ENCODE_QUOTES | FILTER_FLAG_STRIP_HIGH | FILTER_FLAG_STRIP_LOW);

That’s it. Nothing magical.

The same goes for passing a flags field in an options array in the case of using callbacks. Here is an extended version of the example from php.net:

$var = filter_var($string, FILTER_SANITIZE_SPECIAL_CHARS,
array('flags' => FILTER_FLAG_STRIP_LOW | FILTER_FLAG_ENCODE_HIGH));

Did you find this post useful or have questions or comments? Please let me know!

Tags: How Tos · php · Programming

2 responses so far ↓

  • 1 Anthony Rutledge // May 8, 2015 at 8:55 pm

    PHP.net should fix its documentation.

  • 2 Leslie Roberts // Oct 31, 2016 at 2:56 pm

    Nicely explained. PHP.net does not explain things very well at all.

Leave a Comment