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 — Adjuntar un filtro a una secuencia
Descripción
Agrega el nombre_filtro a la lista de filtros adjuntos a la secuencia . Este filtro será añadido con los parametros especificados al final de la lista y por lo tanto será llamado al último durante las operaciones de la secuencia. Para agregar un filtro al comienzo de la lista, use stream_filter_prepend().
Por defecto, stream_filter_append() adjuntará el filtro a la cadena de filtros de lectura si el archivo fue abierto para lectura (esto quiere decir, Modo del Archivo: r, o +). El filtro también se adjuntará a la cadena de filtros de escritura si el archivo fue abierto para escritura (esto quiere decir, Modo del Archivo: w, a, O +). Las constantes STREAM_FILTER_READ, STREAM_FILTER_WRITE, o STREAM_FILTER_ALL pueden ser pasadas también al parámetro lectura_escritura para sobrescribir este comportamiento.
A partir de PHP 5.1.0, esta función devuelve un recurso que puede ser usado para referirse a esta instancia de filtro durante una llamada a stream_filter_remove(). Antes de PHP 5.1.0, esta función devuelve TRUE en caso de éxito o FALSE si ocurre un error.
Example #1 Control del lugar en el que se aplican los filtros
<?php
/* Abrir un archivo de prueba para lectura y escritura */
$da = fopen('prueba.txt', 'w+');
/* Aplicar el filtro ROT13 a la cadena de filtros de escritura, pero
* no a la cadena de filtros de lectura */
stream_filter_append($da, "string.rot13", STREAM_FILTER_WRITE);
/* Escribir una cadena simple al archivo, la cual sera transformada
mediante ROT13 en su camino de salida */
fwrite($da, "Esta es una prueba\n");
/* Volver al inicio del archivo */
rewind($da);
/* Leer los contenidos del archivo de vuelta. Si hubiesemos aplicado
* el filtro a la cadena de filtros de lectura tambien, veriamos el
* texto de vuelta a su estado original debido a la retransformacion
* con ROT133 */
fpassthru($da);
fclose($da);
/* Salida Esperada
---------------
Rfgn rf han cehron
*/
?>
Note: Cuando se usan filtros personalizados (de usuario)
La función stream_filter_register() debe ser llamada primero para registrar el filtro de usuario deseado para nombre_filtro .
Note: Los datos de la secuencia son leídos desde los recursos (tanto locales como remotos) en paquetes, usando búferes internos para conservar todos los datos sin consumir. Cuando un nuevo filtro es agregado a la secuencia, los datos en los búferes internos son procesados a través del nuevo filtro en ese momento. Este comportamiento difiere de aquél de stream_filter_prepend().
Vea también stream_filter_register(), stream_filter_prepend(), y stream_get_filters().
stream_filter_append
23-Jul-2008 09:20
13-Dec-2005 07:47
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
