O'Reilly logo

Upgrading to PHP 5 by Adam Trachtenberg

Stay ahead with the world's most comprehensive technology and business learning platform.

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, tutorials, and more.

Start Free Trial

No credit card required

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

Method

Description

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 ...

With Safari, you learn the way you learn best. Get unlimited access to videos, live online training, learning paths, books, interactive tutorials, and more.

Start Free Trial

No credit card required