Php flush all buffers

flush

Функция очищает системный буфер вывода PHP, при этом всё содержимое буфера отправляется в браузер пользователя (с некоторыми исключениями), независимо от используемого backend-а у PHP (CGI, web-сервер и т.д.).

flush() не может изменить схему буферизации вашего web-сервера и никак не влияет на буферизацию браузера на стороне клиента. Функция так же не влияет на механизм буферизации пользовательского PHP кода. Это означает, что если вы используете сброс выходных буферов ob, то вам придется вызывать ob_flush() и flush() вместе.

Некоторые серверы, особенно под управлением Win32, будут по-прежнему продолжать буферизировать вывод вашего скрипта до передачи результатов в браузер.

Серверные модули для Apache, такие как mod_gzip, могут сами выполнять буферизацию, поэтому flush() не приводит к немедленной передаче данных клиенту.

Некоторые версии Microsoft Internet Explorer начинают отображать страницу только после получения 256 байт вывода, поэтому может понадобиться отправить дополнительные пробелы перед сбросом, чтобы такие браузеры отобразили страницу.

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

Эта функция не возвращает значения после выполнения.

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

  • ob_flush() — Сброс (отправка) буфера вывода
  • ob_clean() — Очищает (стирает) буфер вывода
  • ob_end_flush() — Сброс (отправка) буфера вывода и отключение буферизации вывода
  • ob_end_clean() — Очищает (стирает) буфер вывода и отключает буферизацию вывода

Источник

ob_flush

This function will send the contents of the output buffer (if any). If you want to further process the buffer’s contents you have to call ob_get_contents() before ob_flush() as the buffer contents are discarded after ob_flush() is called.

Читайте также:  Html css text margins

This function does not destroy the output buffer like ob_end_flush() does.

Parameters

This function has no parameters.

Return Values

Returns true on success or false on failure.

See Also

  • ob_get_contents() — Return the contents of the output buffer
  • ob_clean() — Clean (erase) the output buffer
  • ob_end_flush() — Flush (send) the output buffer and turn off output buffering
  • ob_end_clean() — Clean (erase) the output buffer and turn off output buffering

User Contributed Notes 14 notes

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.

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:
header ( ‘Content-type: text/html; charset=utf-8’ );
echo ‘Begin .
‘ ;
for( $i = 0 ; $i < 10 ; $i ++ )
echo $i . ‘
‘ ;
flush ();
ob_flush ();
sleep ( 1 );
>
echo ‘End .
‘ ;
?>

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.

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()`.

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.

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):

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:

// 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.

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.

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

Enjoy

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:


php_flag zlib.output_compression off
php_value max_execution_time 3000
php_value max_input_time 3000

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 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:

ob_implicit_flush ();
ob_end_flush ();
?> [1013 more characters] 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:

header ( «Content-type: text/plain» );
.
?>

Then it won’t care whether you sent a body tag, it will just wait for 1019 characters.

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.

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.

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:

ob_start ();
echo ‘Hello World!’
?>

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

  • Output Control Functions
    • flush
    • ob_​clean
    • ob_​end_​clean
    • ob_​end_​flush
    • ob_​flush
    • ob_​get_​clean
    • ob_​get_​contents
    • ob_​get_​flush
    • ob_​get_​length
    • ob_​get_​level
    • ob_​get_​status
    • ob_​gzhandler
    • ob_​implicit_​flush
    • ob_​list_​handlers
    • ob_​start
    • output_​add_​rewrite_​var
    • output_​reset_​rewrite_​vars

    Источник

    ob_end_flush

    This function will send the contents of the topmost output buffer (if any) and turn this output buffer off. If you want to further process the buffer’s contents you have to call ob_get_contents() before ob_end_flush() as the buffer contents are discarded after ob_end_flush() is called.

    The output buffer must be started by ob_start() with PHP_OUTPUT_HANDLER_FLUSHABLE and PHP_OUTPUT_HANDLER_REMOVABLE flags. Otherwise ob_end_flush() will not work.

    Note: This function is similar to ob_get_flush() , except that ob_get_flush() returns the buffer as a string.

    Parameters

    This function has no parameters.

    Return Values

    Returns true on success or false on failure. Reasons for failure are first that you called the function without an active buffer or that for some reason a buffer could not be deleted (possible for special buffer).

    Errors/Exceptions

    If the function fails it generates an E_NOTICE .

    Examples

    Example #1 ob_end_flush() example

    The following example shows an easy way to flush and end all output buffers:

    See Also

    • ob_start() — Turn on output buffering
    • ob_get_contents() — Return the contents of the output buffer
    • ob_get_flush() — Flush the output buffer, return it as a string and turn off output buffering
    • ob_flush() — Flush (send) the output buffer
    • ob_end_clean() — Clean (erase) the output buffer and turn off output buffering

    User Contributed Notes 9 notes

    A note on the above example.

    with PHP 4 >= 4.2.0, PHP 5 you can use a combination of ob_get_level() and ob_end_flush() to avoid using the @ (error suppresion) which should probably be a little faaster.

    while ( ob_get_level () > 0 ) ob_end_flush ();
    >

    best way to compress a css code:

    header ( ‘Content-type: text/css’ );

    ob_start ( «compress» );
    function compress ( $buffer ) // remove comments
    $buffer = preg_replace ( ‘!/\*[^*]*\*+([^/][^*]*\*+)*/!’ , » , $buffer );
    // remove tabs, spaces, newlines, etc.
    $buffer = str_replace (array( «\r\n» , «\r» , «\n» , «\t» , ‘ ‘ , ‘ ‘ , ‘ ‘ ), » , $buffer );
    return $buffer ;
    >

    include( ‘./template/main.css’ );
    include( ‘./template/classes.css’ );

    Apart from being mostly redundant, ob_end_flush() can be downright damaging in some weird cases.

    Actual example: a particular page on an Intranet website which would appear blank on Internet Explorer 6 when ob_start(‘ob_gzhandler’) was called in the beginning and ob_end_flush() at the end.

    We couldn’t figure out what made that page special no matter what we tried. The ob_ functions were placed in scripts which were include()’d by all pages just the same, but only that page did this.

    Even stranger, the problem only appeared on direct browser/server connections. Whenever the connection passed through a proxy the problem dissapeared. I’m guessing some kind of HTTP encoding headers mumbo-jumbo.

    Solution: unless you really need it in particular cases, remove the ob_end_flush() call and rely on the builtin, automatic buffer flush.

    It appears that you can call ob_end_flush() regardless of whether or not output buffering was ever started using ob_start(). This can prove useful because it saves you from having to create conditional statements based on whether a particular function or include file has started output buffering. You can simply call the ob_end_flush() anyway and if there’s output in the buffer, it will be sent, otherwise your script will just keep on keepin’ on.

    Wanted to speed things up and put some processing after the page has been delivered to the client. That drove me almost insane, but finally, I found a solution (php 5.2.5):

    ob_start (); // outer buffer
    ob_start (); // inner buffer to catch URL rewrites and other post processing
    session_start (); // registers URL rewriter with inner buffer!
    echo ‘. ‘ ;
    // log performance data to log files *after* delivering the page!
    register_shutdown_function (array( $benchmarkclass , ‘log_perf_data’ ));
    // now flush output output to client
    ob_end_flush ();
    // need to calculate content length *after* URL rewrite!
    header ( «Content-length: » . ob_get_length ());
    ob_end_flush ();
    // now we close the session and do some arbitrary clean-up tasks
    // registered using register_shutdown_function()
    session_write_close ();
    ?>

    Источник

Оцените статью