HOW TO Use Multiple Filter Flags in PHP Filter Functions

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!

This entry was posted in How Tos, php, Programming. Bookmark the permalink.

2 Responses to HOW TO Use Multiple Filter Flags in PHP Filter Functions

  1. PHP.net should fix its documentation.

  2. Leslie Roberts says:

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

Leave a Reply

Your email address will not be published.