stream_filter_append

(PHP 4 >= 4.3.0, PHP 5)

stream_filter_appendПрикрепляет фильтр к потоку

Описание

resource stream_filter_append ( resource $stream , string $filtername [, int $read_write [, mixed $params ]] )

Добавляет filtername в список фильтров, прикреплённых к stream.

Список параметров

stream

Целевой поток.

filtername

Название фильтра.

read_write

По умолчанию stream_filter_append() будет прикреплять фильтр к цепочке фильтров чтения, если файл был открыт для чтения (т. е. режим файла: r, и/или +). Фильтр также будет прикреплён к цепочке фильтров записи, если файл был открыт для записи (т. е. режим файла: w, a, и/или +). Константы STREAM_FILTER_READ, STREAM_FILTER_WRITE, и/или STREAM_FILTER_ALL также могут быть переданы в параметре read_write, чтобы переопределить это поведение.

params

Этот фильтр будет добавлен с указанными params к концу списка и, таким образом, будет вызван последним в списке потоковых операций. Чтобы добавить фильтр в начало списка, используйте stream_filter_prepend().

Возвращаемые значения

Возвращает ресурс, который может быть использован для того, чтобы обратиться к этому экземпляру фильтра во время вызова stream_filter_remove().

Список изменений

Версия Описание
5.1.0 До PHP 5.1.0 эта функция возвращает TRUE в случае успешного выполнения или FALSE в случае возникновения ошибки.

Примеры

Пример #1 Контроль применения фильтров

<?php
/* Открываем тестовый файл для чтения и записи */
$fp fopen('test.txt''w+');

/* Прикрепляем фильтр ROT13 к
 * цепочке фильтров записи, но не к
 * цепочке фильтров чтения */
stream_filter_append($fp"string.rot13"STREAM_FILTER_WRITE);

/* Запишем простую строку в файл
 * она будет преобразована при помощи ROT13
 * на выходе */
fwrite($fp"Это тест\n");

/* Назад к началу файла */
rewind($fp);

/* Прочитаем содержимое файла.
 * Если фильтр также был бы прикреплён к
 * цепочке фильтров чтения, мы бы увидели
 * преобразованный при помощи ROT13 текст в исходном состоянии */
fpassthru($fp);

fclose($fp);

/* Ожидаемый вывод
   ---------------

Guvf vf n grfg

 */
?>

Примечания

Замечание: При использовании пользовательских фильтров
Сначала должна быть вызвана функция stream_filter_register() для того, чтобы зарегистрировать желаемый пользовательский фильтр на имя filtername.

Замечание: Потоковые данные читаются из ресурсов (и локальных, и удалённых) по кускам, и любые невостребованные данные сохраняются во внутренних буферах. Когда новый фильтр добавляется в конец потока, то данные во внутренних буферах обрабатываются через новый фильтр. Это отличается от поведения функции stream_filter_prepend().

Замечание: Когда фильтр добавляется для чтения и записи, создаются два экземпляра фильтра. Функция stream_filter_append() должна быть вызвана дважды с STREAM_FILTER_READ и STREAM_FILTER_WRITE чтобы получить оба ресурса фильтра.

Смотрите также

Коментарии

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 writtenthen 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
2005-12-13 00:47:00
http://php5.kiev.ua/manual/ru/function.stream-filter-append.html
Автор:
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);
}
?>
2008-07-23 03:20:38
http://php5.kiev.ua/manual/ru/function.stream-filter-append.html
Автор:
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"

fprintfSTDOUT"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:
function.ob-start

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
2016-01-11 21:23:07
http://php5.kiev.ua/manual/ru/function.stream-filter-append.html
Автор:
Available internal filters are listed here :

https://www.php.net/manual/filters.php
2022-02-10 00:10:50
http://php5.kiev.ua/manual/ru/function.stream-filter-append.html
Автор:
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.
2023-01-15 12:49:19
http://php5.kiev.ua/manual/ru/function.stream-filter-append.html

    Поддержать сайт на родительском проекте КГБ