ob_flush

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

ob_flushСбрасывает (отправляет) возвращённое активным обработчиком вывода значение

Описание

ob_flush(): bool

Функция вызывает обработчик вывода (с флагом the PHP_OUTPUT_HANDLER_FLUSH), сбрасывает (отправляет) возвращённое им значение и удаляет содержимое активного буфера вывода.

Функция не отключает активный буфер вывода, как это делают функции ob_end_flush() или ob_get_flush().

Функция ob_flush() завершится неудачно, если активный буфер вывода был запущен без флага PHP_OUTPUT_HANDLER_FLUSHABLE.

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

У этой функции нет параметров.

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

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки.

Ошибки

Если функция завершается неудачно, она выдаёт ошибку уровня E_NOTICE.

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

  • ob_start() - Включает буферизацию вывода
  • ob_get_contents() - Возвращает содержимое буфера вывода
  • ob_end_flush() - Сбрасывает (отправляет) возвращаемое значение активного обработчика вывода и отключает активный буфер вывода
  • ob_get_flush() - Сбрасывает (отправляет) возвращённое активным обработчиком вывода значение, возвращает содержимое активного буфера вывода и отключает его
  • ob_clean() - Очищает (стирает) содержимое активного буфера вывода

add a note add a note

User Contributed Notes 15 notes

up
44
Lee
12 years ago
As of August 2012, all browsers seem to show an all-or-nothing approach to buffering. In other words, while php is operating, no content can be shown.

In particular this means that the following workarounds listed further down here are ineffective:

1) ob_flush (),  flush () in any combination with other output buffering functions;

2) changes to php.ini involving setting output_buffer and/or zlib.output_compression to 0 or Off;

3) setting Apache variables such as "no-gzip" either through apache_setenv () or through entries in .htaccess.

So, until browsers begin to show buffered content again, the tips listed here are moot.
up
40
dermeister dot online at gmail dot com
12 years ago
some problems with ob_flush() and flush() could be resolved by defining content type header :
header( 'Content-type: text/html; charset=utf-8' );

so working code looks like this:
<?php
header
( 'Content-type: text/html; charset=utf-8' );
echo
'Begin ...<br />';
for(
$i = 0 ; $i < 10 ; $i++ )
{
    echo
$i . '<br />';
   
flush();
   
ob_flush();
   
sleep(1);
}
echo
'End ...<br />';
?>
up
12
chris - latko - org
9 years ago
Although browsers now have an all or none buffering strategy, the arguments are not moot.

If you are not using ob_flush, you run this risk of exceeding socket timeouts (commonly seen in php-fpm/nginx combos).

Basically, flushing solves the infamous 504 Gateway Time-out error.
up
2
jake at qzdesign dot co dot uk
6 years ago
If there is no active output buffer, an error of level E_NOTICE is generated (at least in PHP 7.1).  To avoid this, test first with `ob_get_level()`.
up
3
riimeik
14 years ago
If you're still not getting the buffer work correctly then try to clean all the others before starting your own (and even if PHP tells you that there are no buffers active):

while(@ob_end_clean());
up
5
Jens
16 years ago
If you call ob_flush() and flush() and still dont get the buffer flushed it might be because some antivirus software (Panda in this case) holds the buffer until the page has finished loaded before sending it to the browser.
up
1
thecichos at gmail dot com
1 year ago
The output buffer seems to work best when the server is returning a code 206 and setting the output_buffering lower temporarily to let it fill up

This tells the browser to wait for additional content
for example:
// Set the header to 206
header("HTTP/1.1 206 Partial Content; Content-Type: text/html; charset=utf-8");

// Flush the current outputbuffer
flush();
ob_flush();
ob_end_flush();
           
// Create a new output buffer
ob_start();

// Save the current output buffer size
$tempBuffering = ini_get("output_buffering");
           
// Set a new, much smaller buffer size
ini_set("output_buffering", 256);

// Do some buffering
!!!   All your amazing code goes here   !!!

// Fill the buffer with something if needed
echo str_pad(" ", (int)ini_get("output_buffering"), " ");
flush();
ob_flush();

// Revert the buffer size
ini_set("output_buffering", $tempBuffering);
up
-1
Anonymous
19 years ago
I was having problems with output buffering which seemed to be active by default on the server, although phpinfo said something else..

In any case I needed to know that when I ran ob_start, it would start at the top level, so I could use ob_flush as it's intended without having to call multiple ob_flush in-script - this is what I did:

<?php

// make sure output buffering is off before we start it
// this will ensure same effect whether or not ob is enabled already
while (ob_get_level()) {
   
ob_end_flush();
}
// start output buffering
if (ob_get_length() === false) {
   
ob_start();
}

?>

Then I could call ob_flush(); followed by flush(); and get the output I wanted, which I didn't if I started the script with just ob_start();

This was on a windows apache 2 server with php 5.0.4 btw.
up
-6
sebastian at jcompare dot com
15 years ago
For some reason, calling just flush or ob_flush or even both together did not get my output buffers flushed, and calling ob_end_flush by itself didn't work either but calling them all worked well. Here is my new output flushing function.

<?php
function flush_buffers(){
   
ob_end_flush();
   
ob_flush();
   
flush();
   
ob_start();
}
?>

Enjoy
up
-7
Anonymous
19 years ago
You must call them in the correct order.
ob_flush();
flush();
up
-3
colnector at@ colnect punto com
16 years ago
As stated in flush() manual entry, if php compresses the ouput with zlib this function may be ineffective.

A possible option for folders on your server that have scripts which may take a long time to run is to add the following in your relevant .htaccess file:

<FilesMatch "\.(php|html?)$">
php_flag zlib.output_compression off
php_value max_execution_time 3000
php_value max_input_time 3000
</FilesMatch>
up
-4
Reynard Hilman
19 years ago
when using command line php, if somewhere in your script you have ob_start(), you have to call ob_end_flush() first, and then you can call these functions:
flush();
ob_flush();

without calling ob_end_flush first, flush and ob_flush does not have any effect, at least that's what I experienced.
up
-7
cesoid at gmail dot com
11 years ago
Currently I have Chrome on OS X Snow Leopard updating a page as it is sent more data, BUT it only does this after I send it <body> along with 1013 more characters (making 1019 total characters). After it receives this it immediately displays it and then displays anything else as it is received. (Note that this browser-operating system combination isn't necessarily the only one, it's just the only one I've tested.)

In order to do this using php, I've done nothing but send ob_flush() after each echo or print. I can also make it happen without ob_flush() by calling ob_implicit_flush(), then ob_end_flush() before print, and then it updates with each print after that. I have pretty typical settings and I change none of them when the file runs, it literally looks like this:

<?php
  ob_implicit_flush
();
 
ob_end_flush();
 
?><body>[1013 more characters]<?php
 
for ($i = 1; $i < 30000000; ++$i) {}
  echo
"something that didn't show up immediately";
?>

(Ok, the "[1013 more characters]" part wasn't strictly literal.)

If you want just text in the browser, you do this before everything else:

<?php
header
("Content-type: text/plain");
...
?>

Then it won't care whether you sent a body tag, it will just wait for 1019 characters.
up
-8
jeremy at e2-media dot co dot nz
19 years ago
we had problems with flushing data to the browser. a simple call to ob_flush() or flush() would not work. We found that repeatly calling theses fuctions did work however.

<?
flush
();
ob_flush();
flush();
ob_flush();
flush();
ob_flush();
?>

go figure!
up
-26
kel at no-spam dot newcastleinfotech dot com dot au
16 years ago
Also note that any data in the buffer will flush at the end of the script, not destroyed, so it is often not necessary to call ob_flush(); for example:

<?php
ob_start
();
echo
'Hello World!'
?>

Will still result in Hello World! being displayed to the browser.
To Top