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);
}
?>
stream_filter_append
(PHP 4 >= 4.3.0, PHP 5)
stream_filter_append — Enlaza un filtro a un flujo
Descripción
$stream
, string $filtername
[, int $read_write
[, mixed $params
]] )
Añade filtername a la lista de filtros
enlazados 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/oSTREAM_FILTER_ALLtambién se pueden pasar al parámetroread_writepara sobrescribir este comportamiento. -
params -
Este filtro será añadido con los parámetros
paramsespecificados 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 que puede ser usado para hacer referencia a esta instancia de filtro durante una llamada a stream_filter_remove().
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 enfiltername.
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_READySTREAM_FILTER_WRITEpara obtener ambos recursos del filtro.
Ver también
- stream_filter_register() - Registrar un filtro de flujo definido por el usuario
- stream_filter_prepend() - Enlaza un filtro a un flujo
- stream_get_filters() - Recuperar la lista de los filtros registrados
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
