stream_filter_register()

stream_filter_register() — Register a user defined stream filter.

Built-in function of PHP 8.5. The manual lists it as available in PHP 5, PHP 7, PHP 8. This page is the reference card: signature, parameters and return value, plus the changelog and the example the manual provides.

What it does

stream_filter_register() allows you to implement your own filter on any registered stream used with all the other filesystem functions (such as fopen(), fread() etc.).

Signature

stream_filter_register(string $filter_name, string $class): bool

Parameters

ParameterTypeWhat it takes
$filter_namestringThe filter name to be registered.
$classstringTo implement a filter, you need to define a class as an extension of php_user_filter with a number of member functions. When performing read/write operations on the stream to which your filter is attached, PHP will pass the data through your filter (and any other filters attached to that stream) so that the data may be modified as desired. You must implement the methods exactly as described in php_user_filter - ...

Return value

Returns true on success or false on failure. stream_filter_register() will return false if the filter_name is already defined.

Example

A runnable snippet:

/* Define our filter class */ class strtoupper_filter extends php_user_filter { function filter($in, $out, &$consumed, $closing) { while ($bucket = stream_bucket_make_writeable($in)) { $bucket->data = strtoupper($bucket->data); $consumed += $bucket->datalen; stream_bucket_append($out, $bucket); } return PSFS_PASS_ON; } } /* Register our filter with PHP */ stream_filter_register("strtoupper", "strtoupper_filter") or die("Failed to register filter"); $fp = fopen("foo-bar.txt", "w"); /* Attach the registered filter to the stream just opened */ stream_filter_append($fp, "strtoupper"); fwrite($fp, "Line1\n"); fwrite($fp, "Word - 2\n"); fwrite($fp, "Easy As 123\n"); fclose($fp); /* Read the contents back out */ readfile("foo-bar.txt");

Output:

LINE1 WORD - 2 EASY AS 123

See also

stream_wrapper_register(), stream_filter_append(), stream_filter_prepend()

All PHP 8.5 built-in functions

Reference card built from the PHP manual page stream_filter_register() (PHP documentation, CC BY 3.0). The page is generated from the manual, so the wording of the parameter and return value text follows php.net.