Creating Filters

PHP 5 comes with very few stream filters, but it introduces the ability to write your own filters in PHP, effectively giving you unlimited possibilities. PHP 4 requires all filters to be implemented in C.

The filter interface is much less complex than the wrapper interface. It has only three different methods, and it’s common to implement only a single method, filter( ). Table 8-3 contains an overview of the API.

Table 8-3. Filter methods



int filter(resource in, resource out, int &consumed, bool closing)

Called during data filtering; may be called multiple times per stream

void onCreate(void)

Called during filter instantiation

void onClose(void)

Called during filter destruction

The filter( ) method is where all the action takes place. Inside this method, you’re required to process the incoming data, filter it when you can, and then alert the filter of your progress.

This section shows how to implement two different filters: one that encodes special characters (such as & and <) to their HTML entities equivalents, and one the does the reverse, by transforming HTML entities back into characters.

Converting to HTML Entities

Example 8-6 shows a filter that encodes HTML entities using the htmlentities( ) function.

Example 8-6. Encoding HTML entities with a filter

class htmlentitiesFilter extends php_user_filter { function filter($in, $out, &$consumed, $closing) { while ($bucket = stream_bucket_make_writeable($in)) { $bucket->data ...

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

O’Reilly members experience live online training, plus books, videos, and digital content from 200+ publishers.