downloads | documentation | faq | getting help | mailing lists | licenses | wiki | reporting bugs | php.net sites | links | conferences | my php.net

search for in the

flush> <PDO_OCI DSN
[edit] Last updated: Mon, 01 Nov 2010

view this page in

CXI. Bufferisation de sortie

Introduction

Les fonctions de bufferisation de sortie vous permettent de contrôler quand les données ont été envoyées par le script. Cela peut être utile dans certaines situations, notamment si vous devez envoyer des en-têtes au navigateur après avoir envoyé des données. Ces fonctions n'affectent pas les en-têtes envoyés par la fonction header() ou les cookies envoyés par setcookie(). Seules les fonctions telles que echo() et les données entre blocs PHP sont affectées.

Pré-requis

Ces fonctions sont disponibles dans le module PHP standard, qui est toujours accessible.

Installation

Il n'y pas d'installation nécessaire pour utiliser ces fonctions, elles font parties du coeur de PHP.

Configuration à l'exécution

Le comportement de ces fonctions est affecté par la configuration dans le fichier php.ini.

Tableau 1. Options de configuration

NomPar défautModifiableHistorique
output_buffering"0"PHP_INI_PERDIR 
output_handlerNULLPHP_INI_PERDIRDisponible depuis PHP 4.0.4.
implicit_flush"0"PHP_INI_ALLPHP_INI_PERDIR en PHP <= 4.2.3.
Pour plus de détails sur les constantes PHP_INI_*, reportez-vous à Annexe G.

Voici un éclaircissement sur l'utilisation des directives de configuration.

output_buffering booléen/entier

Vous pouvez activer la bufferisation de sortie pour tous les fichiers avec cette directive, en lui passant la valeur On. Si vous souhaitez limiter la taille du buffer à une certaine taille, vous pouvez alors indiquer un nombre maximum d'octets à la place de On. Par exemple, output_buffering=4096). Depuis PHP 4.3.5, cette directive est toujours désactivée en ligne de commande.

output_handler string

Vous pouvez rediriger le résultat de tous vos scripts à une fonction avant leur envoi au navigateur. Par exemple, si vous configurez output_handler à mb_output_handler(), l'encodage des caractères sera adapté de manière transparente. Configurer une telle fonction active automatiquement la bufferisation de sortie.

Note : Vous ne pouvez pas utiliser simultanément mb_output_handler() avec ob_iconv_handler(), non plus que ob_gzhandler() avec zlib.output_compression.

Note : Seules les fonctions internes peuvent être utilisées avec cette directive. Pour les fonctions utilisateurs, utilisez ob_start().

implicit_flush booléen

FALSE par défaut. En changeant cette valeur pour TRUE vous indiquez à PHP que le buffer de sortie doit être vidé automatiquement après chaque fonction d'affichage. Cela revient à appeler la fonction flush() après chaque appel à print() ou echo() et pour tous les blocs HTML.

Lorsque vous utilisez PHP en environnement web, activer cette option a de sérieuses implications et généralement, cela n'est conseillé que pour les débogage. Cette valeur est par défaut à TRUE lorsque PHP fonctionne en mode CLI SAPI.

Voir aussi ob_implicit_flush().

Types de ressources

Cette extension ne définit aucune ressource.

Constantes pré-définies

Cette extension ne définit aucune constante.

Exemples

Exemple 1. Exemple de bufferisation de sortie

<?php

ob_start
();
echo
"Bonjour\n";

setcookie("nom_du_cookie", "valeur_du_cookie");

ob_end_flush();

?>

Dans l'exemple ci-dessus, la fonction echo() est stockée dans un buffer jusqu'à l'appel de la fonction ob_end_flush(). Dans le même temps, l'appel à setcookie() a réussi à créer un cookie, sans générer d'erreur. (D'habitude, vous devez envoyer les en-têtes avant les données).

Note : Lorsque vous passez de PHP 4.1 ou 4.2 à 4.3, assurez-vous que implict_flush est à OFF dans votre php.ini, sinon la fonction ob_start() ne masquera pas les affichages engendrés.

Table des matières
flush -- Vide les tampons de sortie
ob_clean --  Efface le tampon de sortie
ob_end_clean --  Détruit les données du tampon de sortie et éteint la tamporisation de sortie
ob_end_flush --  Envoie les données du tampon de sortie et éteint la tamporisation de sortie
ob_flush -- Envoie le tampon de sortie
ob_get_clean --  Lit le contenu courant du tampon de sortie puis l'efface
ob_get_contents --  Retourne le contenu du tampon de sortie
ob_get_flush --  Vide le tampon, le retourne en tant que chaîne et stoppe la tamporisation
ob_get_length --  Retourne la longueur du contenu du tampon de sortie
ob_get_level --  Retourne le nombre de niveaux d'imbrications du système de tamporisation de sortie
ob_get_status -- Lit le statut du tampon de sortie
ob_gzhandler --  Fonction de callback pour la compression automatique des tampons
ob_implicit_flush --  Active/désactive l'envoi implicite
ob_list_handlers --  Liste les gestionnaires d'affichage utilisés
ob_start -- Enclenche la tamporisation de sortie
output_add_rewrite_var --  Ajoute une règle de réécriture d'URL
output_reset_rewrite_vars --  Annule la réécriture d'URL


flush> <PDO_OCI DSN
[edit] Last updated: Mon, 01 Nov 2010
 
add a note add a note User Contributed Notes Bufferisation de sortie
Anonymous 20-Apr-2009 12:24
You possibly also want to end your benchmark after the output is flushed.

<?php
your_benchmark_start_function
();

ob_start ();
for (
$i = 0; $i < 5000; $i++)
    echo
str_repeat ("your string blablabla bla bla", (rand() % 4) + 1)."<br>\n";

                              <----------
echo
your_benchmark_end_function();      |
ob_end_flush (); ------------------------
?>
della at sun dot com 25-Nov-2008 01:08
Sometimes users are blaming about slow pages ... not being aware that mostly this is due to network issues.
So I've decided to add some statistics at the end of my pages:

At beginning I start the counters:

<?php
 
function microtime_float() {
    if (
version_compare(PHP_VERSION, '5.0.0', '>'))  return microtime(true);
    list(
$u,$s)=explode(' ',microtime()); return ((float)$u+(float)$s); 
  }
 
$initime=microtime_float();
 
ob_start();
 
ob_implicit_flush();
?>

And at the end I show the statistics:

<?php
 
echo "PHP Time: ".round((microtime_float()-$initime)*1000)." msecs. ";
  echo
"Size: ".round_byte(strlen(ob_get_contents()));
 
ob_end_flush();
?>

(round_byte is my function to print byte sizes)
jgeewax a t gmail 29-Jun-2007 07:02
It seems that while using output buffering, an included file which calls die() before the output buffer is closed is flushed rather than cleaned. That is, ob_end_flush() is called by default.

<?php
// a.php (this file should never display anything)
ob_start();
include(
'b.php');
ob_end_clean();
?>

<?php
// b.php
print "b";
die();
?>

This ends up printing "b" rather than nothing as ob_end_flush() is called instead of ob_end_clean(). That is, die() flushes the buffer rather than cleans it. This took me a while to determine what was causing the flush, so I thought I'd share.
basicartsstudios at hotmail dot com 28-Jan-2007 12:45
Please note that most browsers don't display a table unless they passed its end-tag "</table>".

Thats why using this feature in HTML-tables might not result in what you expected...

best regards
BasicArtsStudios
basicartsstudios at hotmail dot com 21-Jan-2007 10:39
Sometimes you might not want to include a php-file under the specifications defined in the functions include() or require(), but you might want to have in return the string that the script in the file "echoes".

Include() and require() both directly put out the evaluated code.

For avoiding this, try output-buffering:
<?php
ob_start
();
eval(
file_get_contents($file));
$result = ob_get_contents();
ob_end_clean();
?>
or
<?php
ob_start
();
include(
$file);
$result = ob_get_contents();
ob_end_clean();
?>
which i consider the same, correct me if I'm wrong.

Best regards, BasicArtsStudios
trucex [um, at] gmail [um, dot] com 16-Sep-2006 02:08
Unfortunately, the PHP guys didn't build support into any of the image output functions to return the image instead of outputting it.

Fortunately, we have output buffering to fix that.

<?php

$im
= imagecreatetruecolor(200, 200);

// Other image functions here...

ob_start();
imagepng($im);
$imageData = ob_get_contents();
ob_clean();

?>

You can now use the $imageData variable to either create another GD image, save it, put it in a database, make modifications to the binary, or output it to the user. You can easily check the size of it as well without having to access the disk...just use strlen();
webmaster at wistex dot com 07-Sep-2006 04:07
Now this just blew my mind. I had a problem with MySQL being incredibly slow on Windows 2003 running IIS... on ASP/VBScript pages. PHP is also installed on the server and so is Microsoft SQL 2005 Express. (Yes, we're running ASP, PHP, MySQL and MS SQL on the same Windows 2003 Server using IIS.)

I was browsing the internet for a solution and saw a suggestion that I change output_buffering to on if MySQL was slow for PHP pages.  Since we also served PHP pages with MySQL from the same server, it caught my eye.  For the hell of it, I went into php.ini and changed output_buffering to on and suddenly MySQL and ASP was faster... MySQL and PHP was faster... Microsoft SQL Server 2005 Express and ASP was faster.... everything was faster... even stuff that had no PHP!

And I didn't even have to restart IIS. As soon as I saved the php.ini file with the change, everything got faster.

Apparently PHP and MySQL and IIS are so intertwined somehow that changing the buffering setting really effects the performance of the entire server.

So, if you are having performance problems on Windows 2003 & IIS, you might try setting output_buffering = On in php.ini if you happen to have PHP installed.  Having it set to off apparently effects the performance of Windows 2003 and IIS severely... even for webpages that do not use PHP or MySQL.
kamermans at teratechnologies dot net 21-Aug-2006 01:30
Output buffering is set to '4096' instead of 'Off' or '0' by default in the php-5.0.4-10.5 RPM for Fedora Core release 4 (Stentz).  This has cost me much time!
kend52 at verizon dot net 23-Jun-2005 11:25
I ran out of memory, while output buffering and drawing text on imported images. Only the top portion of the 5MP image was displayed by the browser.  Try increasing the memory limit in either the php.ini file( memory_limit = 16M; ) or in the .htaccess file( php_value memory_limit "16M" ). Also see function memory_get_usage() .
gruik at libertysurf dot fr 10-Jul-2004 05:53
For those who are looking for optimization, try using buffered output.

I noticed that an output function call (i.e echo()) is somehow time expensive. When using buffered output, only one output function call is made and it seems to be much faster.
Try this :

<?php
your_benchmark_start_function
();

for (
$i = 0; $i < 5000; $i++)
    echo
str_repeat ("your string blablabla bla bla", (rand() % 4) + 1)."<br>\n";

echo
your_benchmark_end_function();
?>

And then :

<?php
your_benchmark_start_function
();

ob_start ();
for (
$i = 0; $i < 5000; $i++)
    echo
str_repeat ("your string blablabla bla bla", (rand() % 4) + 1)."<br>\n";

echo
your_benchmark_end_function();
ob_end_flush ();
?>
tijmen 09-Jul-2003 04:44
Trying to benchmark your server when using output_buffering ?
Don't forget that the value 4096 in the php.ini will give you complete different loadtimes compares to the value of 1.
In the first case the output will be sent after buffering 4096 and the loadtime timed at the end of the page will contain the loadtime needed to download the complete page in the clientbrowser while the second value will contain the loadtime needed to place the complete page in the buffer. The time needed for sending is not clocked.
This can be very frustrating if you don't see the differance between server and the 1st is using 4096 instead of 1.
Although technically much faster than the second server the second server was providing much better loadtime results.
This result will grow when using large amounts of output.
But this becomes interesting if you want to measure the time needed for the page to be loaded for the client.

 
show source | credits | sitemap | contact | advertising | mirror sites