stream_filter_append

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

stream_filter_appendAttache un filtre à un flux en fin de liste

Description

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

stream_filter_append() ajoute le filtre filtername à la liste de filtres attachés au flux stream.

Liste de paramètres

stream

Le flux cible.

filtername

Le nom du filtre.

read_write

Par défaut, stream_filter_append() va ajouter le filtre à la liste de filtres de lecture si le fichier a été ouvert en mode lecture (r et/ou +). Le filtre sera aussi attaché à la liste des filtres de lecture si le fichier a été ouvert en mode lecture (w, a et/ou +). STREAM_FILTER_READ, STREAM_FILTER_WRITE, et/ou STREAM_FILTER_ALL peuvent aussi être utilisées dans le paramètre read_write pour contrôler ce comportement.

params

Ce filtre sera ajouté avec les paramètres params à la fin de la liste des filtres, et sera ainsi appelé à la fin des opérations de filtres. Pour ajouter un filtre au début de la liste, utilisez la fonction stream_filter_prepend().

Valeurs de retour

Retourne une ressource en cas de succès, ou false si une erreur survient. La ressource peut être utilisée pour se référer à l'instance de ce filtre lors d'un appel à la fonction stream_filter_remove().

false est retourné si stream n'est pas une ressource ou si filtername ne peut être atteint.

Exemples

Exemple #1 Contrôler l'application des filtres

<?php
// Ouverture d'un fichier de test en lecture/écriture
$fp = fopen('test.txt', 'w+');

/* On applique le filtre ROT13 au flux d'écriture, mais pas à
* celui de lecture */
stream_filter_append($fp, "string.rot13", STREAM_FILTER_WRITE);

/* On ajoute un simple chaîne dans le fichier, il sera
* transformé par ROT13 à l'écriture */
fwrite($fp, "Ceci est un test\n");

/* On revient au début du fichier */
rewind($fp);

/* On lit le contenu du fichier.
* Si on appliquait le filtre ROT13 nous aurions la
* chaîne dans son étât d'origine */
fpassthru($fp);

fclose($fp);

/* Résultat attendu
----------------

Guvf vf n grfg

*/
?>

Notes

Note: Quand vous utilisez des filtres personnalisés
stream_register_filter() doit être appelée avant stream_filter_append() pour enregistrer le filtre sous le nom de filtername.

Note: Les données du flux (locales et distantes) sont retournées en morceaux, les données non acheminées étant conservées dans le tampon interne. Lorsqu'un nouveau filtre est ajouté à la fin du flux, les données dans le tampon interne sont passées dans le nouveau filtre à ce moment-là. Ceci est différent du comportement de stream_filter_prepend().

Note: Quand un filtre est ajouté pour la lecture et l'écriture, deux instances du filtres sont créées. stream_filter_prepend() doit être appelée deux fois avec STREAM_FILTER_READ et STREAM_FILTER_WRITE pour obtenir les ressources de filtres.

Voir aussi

add a note add a note

User Contributed Notes 3 notes

up
6
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
4
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
2
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
To Top