Filtering Streams

Use filters to modify the contents of a stream. They allow you to pre- and postprocess data without altering the original. Stream filters are like output buffer handlers only better, because they’re more flexible and efficient.

Unlike the output buffer handler, which is best suited for information that’s either being printed out or stored in a variable, you can use a filter wherever you can use a stream. This makes it possible to filter, for example, data going to a file. With an output buffer you’d need to store the entire dataset in a buffer, capture it to a variable, and then send it to the file.

You can filter input data as well as output data. PHP’s output buffering only works on output data. A filter lets you automatically encode all HTML entities from a user’s input, for example.

PHP comes with a few built-in filters, but you can also create your own. The built-in filters are:


Performs rot13 encoding


Turns all characters to uppercase


Turns all characters to lowercase


Eliminates HTML tags


Alters the character set using iconv

Use stream_get_filters( ) to determine which filters are available. It works just like stream_get_wrappers( ).

Filters observe an unofficial namespace convention. For instance, string filters begin with string. and conversion filters begin with convert..

To use a filter with a stream, you must associate the two using stream_filter_prepend( ) or stream_filter_append( ...

Get Upgrading to PHP 5 now with the O’Reilly learning platform.

O’Reilly members experience books, live events, courses curated by job role, and more from O’Reilly and nearly 200 top publishers.