PHP Function Reference

PHP stream_filter_append() Function



The PHP stream_filter_append() function adds a filter to the list of filters attached to the given stream. This function adds the specified filter to the end of the list and will therefore be called last during stream operations.

To add the filter to the beginning of the list, stream_filter_prepend() function can be used.

Syntax

stream_filter_append(stream, filtername, read_write, params)

Parameters

stream Required. Specify the target stream.
filtername Required. Specify the filter name.
read_write Required. By default, this function attaches the filter to the read filter chain if the file was opened for reading (i.e. File Mode: r, and/or +). The filter will also be attached to the write filter chain if the file was opened for writing (i.e. File Mode: w, a, and/or +). STREAM_FILTER_READ, STREAM_FILTER_WRITE, and/or STREAM_FILTER_ALL can also be passed to the read_write parameter to override this behavior.
params Optional. This filter will be added with the specified params to the end of the list and will therefore be called last during stream operations.

Return Value

Returns a resource on success or false on failure. Returns false if stream is not a resource or if filtername cannot be located.

Example: controlling where filters are applied

The example below shows the usage of stream_filter_append() function.

<?php
//open a test file for writing
$fp = fopen("test.txt", "w");

//appending 'string.rot13' filter to the file stream 
$rot13_filter = stream_filter_append($fp, "string.rot13", 
                                      STREAM_FILTER_WRITE);

//writing some content with filter attached                                
fwrite($fp, "This is ");

//removing the $rot13_filter filter
stream_filter_remove($rot13_filter);

//writing some content after removing filter
fwrite($fp, "a test\n");

//setting the file pointer to the start
rewind($fp);

//closing the file
fclose($fp);

//reading and displaying the content of the file
echo file_get_contents("test.txt");
?>

The output of the above code will be:

Guvf vf a test

Note: Stream data is read from resources (both local and remote) in chunks, with any unconsumed data kept in internal buffers. When a new filter is appended to a stream, data in the internal buffers is processed through the new filter at that time. This differs from the behavior of stream_filter_prepend().

Note: When a filter is added for read and write, two instances of the filter are created. This function must be called twice with STREAM_FILTER_READ and STREAM_FILTER_WRITE to get both filter resources.

❮ PHP Streams Reference