PHP 8.3.4 Released!

stream_filter_append

(PHP 4 >= 4.3.0, PHP 5, PHP 7, PHP 8)

stream_filter_appendEnlaza un filtro a un flujo

Descripción

stream_filter_append(
    resource $stream,
    string $filtername,
    int $read_write = ?,
    mixed $params = ?
): resource

Añade un nombre de filtro dado por filtername a la lista de filtros adjuntos a stream.

Parámetros

stream

El flujo objetivo.

filtername

El nombre del filtro.

read_write

Por omisión, stream_filter_append() enlazará el filtro a la cadena de filtros de lectura si el archivo fue abierto para lectura (esto es, Modo de Archivo: r, y/o +). El filtro también será enlazado a la cadena de filtros de escritura si el archivo fue abierto para escritura (esto es, Modo de Archivo: w, a, y/o +). STREAM_FILTER_READ, STREAM_FILTER_WRITE, y/o STREAM_FILTER_ALL también se pueden pasar al parámetro read_write para sobrescribir este comportamiento.

params

Este filtro será añadido con los parámetros params especificados al final de la lista y por lo tanto será llamado el último durante las operaciones de flujo. Para añadir un filtro al principio de la lista use stream_filter_prepend().

Valores devueltos

Devuelve un recurso en caso de éxito o false en caso de fallo. El recurso se puede emplear para referirse a esta instnacia del filtro durante una llamada a stream_filter_remove().

Se devuelve false si stream no es un recurso o si filtername no se puede localizar.

Historial de cambios

Versión Descripción
5.1.0 Antes de PHP 5.1.0, esta función devolvía true si se tuvo éxito o false en caso de error.

Ejemplos

Ejemplo #1 Controlar dónde son aplicados los filtros

<?php
/* Abrir un archivo de prueba para lectura y escritura */
$fp = fopen('prueba.txt', 'w+');

/* Aplicar el filtro ROT13 filter a la
* cadena de filtros de escritura, pero no a la
* cadena de filtros de lectura */
stream_filter_append($fp, "string.rot13", STREAM_FILTER_WRITE);

/* Escribir una cadena sencilla al archivo
* será ROT13 transformado a la
* salida */
fwrite($fp, "Esto es una prueba\n");

/* Retroceder al principio del archivo */
rewind($fp);

/* Leer el contenido del archivo desde atrás.
* Si el filtro ha sido aplicado a la
* cadena de filtros de lectura veríamos
* el texto con el filtro ROT13 deshecho a su estado original */
fpassthru($fp);

fclose($fp);

/* Salida esperada
---------------

Rfgb rf han cehron

*/
?>

Notas

Nota: Cuando se usan filtros personalizos (de usuario)
stream_filter_register() debe llamarse primero para registrar el filtro de usuario deseado en filtername.

Nota: La información del flujo se lee desde recursos (locales y remotos) en trozos, con cualquier información sin consumir guardada en bufferes internos. Cuando un nuevo filtro se añade a un flujo, la información en los bufferes internos se procesa a través del nuevo filtro en ese momento. Esto difiere del comportamiento de stream_filter_prepend().

Nota: Cuando un filtro se añade para lectura y escritura, se crean dos instancias del filtro. stream_filter_append() se debe llamar dos veces con STREAM_FILTER_READ y STREAM_FILTER_WRITE para obtener ambos recursos del filtro.

Ver también

add a note

User Contributed Notes 5 notes

up
7
Dan J
8 years ago
Note that stream filters applied to STDOUT are not called when outputting via echo or print.

This is easily demonstrated with the standard ROT13 filter:
<?php
stream_filter_append
( STDOUT, "string.rot13" );

print
"Hello PHP\n";
// Prints "Hello PHP"

fprintf( STDOUT, "Hello PHP\n" );
// Prints "Uryyb CUC"
?>

If you want to filter STDOUT, you may have better luck with an output buffering callback added via ob_start:
http://php.net/manual/en/function.ob-start.php

At the time of this writing, there is an open PHP feature request to support echo and print for stream filters:
https://bugs.php.net/bug.php?id=30583
up
7
dlvoy
15 years ago
While using compression filters on a large set of files during one script invocation i've got
Fatal error: Allowed memory size of xxx bytes exhausted
even when my max memory limit settings was insane high (128MB)

Workaround is to remember to remove filter after work done with stream_filter_remove:

<?php
foreach($lot_of_files as $filename)
{
$fp = fopen($filename, 'rb');
$filter_params = array('level' => 2, 'window' => 15, $memory => 6);
$s_filter = stream_filter_append($fp, 'zlib.deflate', STREAM_FILTER_READ, $filter_params);
// here stream-operating code

stream_filter_remove($s_filter);

fclose($fp);
}
?>
up
4
net_navard at yahoo dot com
18 years ago
Hello firends

The difference betweem adding a stream filter first or last in the filte list in only the order they will be applied to streams.

For example, if you're reading data from a file, and a given filter is placed in first place with stream_filter_prepend()the data will be processed by that filter first.

This example reads out file data and the filter is applied at the beginning of the reading operation:

<?php
/* Open a test file for reading */
$fp = fopen("test.txt", "r");
/* Apply the ROT13 filter to the
* read filter chain, but not the
* write filter chain */
stream_filter_prepend($fp, "string.rot13",
STREAM_FILTER_READ);
// read file data
$contents=fread($fp,1024);
// file data is first filtered and stored in $contents
echo $contents;
fclose($fp);
?>

On the other hand, if stream_filter_append() is used, then the filter will be applied at the end of the data operation. The thing about this is only the order filters are applied to streams. Back to the example, it's not the same thing removing new lines from file data and then counting the number of characters, than performing the inverse process. In this case, the order that filters are applied to stream is important.

This example writes a test string to a file. The filter is applied at the end of the writing operation:

<?php
/* Open a test file for writing */
$fp = fopen("test.txt", "w+");
/* Apply the ROT13 filter to the
* write filter chain, but not the
* read filter chain */
stream_filter_append($fp, "string.rot13",
STREAM_FILTER_WRITE);
/* Write a simple string to the file
* it will be ROT13 transformed at the end of the
stream operation
* way out */
fwrite($fp, "This is a test\n"); // string data is
first written, then ROT13 tranformed and lastly
written to file
/* Back up to the beginning of the file */
rewind($fp);
$contents=fread($fp,512);
fclose($fp);
echo
$contents;
?>

In the first case, data is transformed at the end of the writing operation, while in the second one, data is first filtered and then stored in $contents.

With Regards
Hossein
up
1
Sbastien
2 years ago
Available internal filters are listed here :

https://www.php.net/manual/filters.php
up
0
TingSong
1 year ago
To decompress a gzipped stream:

<?php
$stream
= $s3_client->getReadStream('somefile.csv.gz');
stream_filter_append($stream, 'zlib.inflate', STREAM_FILTER_READ, ['window' => 15+16]);

// read the decompressed line directly
$line = fgets($stream);
$columns = str_getcsv($line);

// process the data in columns
?>

As the doc of zlib https://www.zlib.net/manual.html#Advanced

The 'window' parameter between 8 and 15 specified the window size from 2⁸ to 2¹⁵ bytes. It can be added by 16 for wrapping with gzip header and trailer instead of zlib wrapper.

And, window could be -8..-15 for unwrapping RAW deflate data.
To Top