Php close all buffers

ob_get_clean

Gets the current buffer contents and delete current output buffer.

ob_get_clean() essentially executes both ob_get_contents() and ob_end_clean() .

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

Parameters

This function has no parameters.

Return Values

Returns the contents of the output buffer and end output buffering. If output buffering isn’t active then false is returned.

Examples

Example #1 A simple ob_get_clean() example

$out = ob_get_clean ();
$out = strtolower ( $out );

The above example will output:

See Also

User Contributed Notes 6 notes

The definition should mention that the function also «turns off output buffering», not just cleans it.

Also, don’t forget that you will need to ob_start() again for any successive calls:

ob_start ();
echo «1» ;
$content = ob_get_clean ();

ob_start (); // This is NECESSARY for the next ob_get_clean() to work as intended.
echo «2» ;
$content .= ob_get_clean ();

Without the second ob_start(), the output is 21 .

Keep in mind that output may be buffered by default, depending on how you are running PHP (CGI, CLI, etc.). You can use ob_get_level() to determine if an output buffer has already been started. On most web servers I’ve used, output buffering is already one level deep before my scripts start running.

You should only end as many output buffers as you start. Assuming that your buffer is always the first buffer, or otherwise closing pre-existing buffers, could lead to problems. In PHP 5.5, you can ensure that output buffers are ended properly using a try-finally block.

Something like this is almost guaranteed to break stuff:

// Don’t ever do this!
while ( ob_get_level () > 1 )
ob_end_flush ();
>

$content = ob_get_clean ();
?>

The problem is that number, «1». Using a fixed number there is asking for trouble. Instead, use ob_get_level() to get the number of output buffers applied when your code starts, and return to that number, if you really must use an unknown number of output buffers:

ob_start ();
$saved_ob_level = ob_get_level ();

// Do stuff here:
run_something ();

// If you really must close all of your output buffers except one, this’ll do it:
while ( ob_get_level () > $start_ob_level )
ob_end_flush ();
>

// And now, the final output buffer that belongs to us:
$content = ob_get_clean ();
?>

Источник

ob_end_clean

Эта функция удаляет содержимое самого верхнего буфера вывода и отключает эту буферизацию. Если вы хотите использовать содержимое буфера, то вам необходимо вызвать ob_get_contents() перед ob_end_clean() , так как все содержимое буфера удаляется при вызове ob_end_clean() .

Читайте также:  Html если нажата кнопка

Буфер вывода должен запускаться функцией ob_start() с флагами PHP_OUTPUT_HANDLER_CLEANABLE и PHP_OUTPUT_HANDLER_REMOVABLE. Иначе не сработает ob_end_clean() .

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

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

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

Возвращает true в случае успешного выполнения или false в случае возникновения ошибки. Основной причиной неудачного завершения работы функции является её вызов без активного буфера или если буфер не может быть удалён (специальный тип буфера).

Ошибки

Если функция завершается ошибкой, генерируется E_NOTICE .

Примеры

Следующий пример показывает простой способ избавиться от всех выходных буферов:

Пример #1 Пример использования функции ob_end_clean()

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

  • ob_start() — Включение буферизации вывода
  • ob_get_contents() — Возвращает содержимое буфера вывода
  • ob_flush() — Сбросить (отправить) буфер вывода

User Contributed Notes 12 notes

Note that if you started called ob_start with a callback, that callback will still be called even if you discard the OB with ob_end_clean.

Because there is no way of removing the callback from the OB once you’ve set it, the only way to stop the callback function from having any effect is to do something like:

$ignore_callback = false ;
ob_start ( ‘my_callback’ );
.
if( $need_to_abort ) $ignore_callback = true ;
ob_end_clean ();
.
>

Take note that if you change zlib output compression setting in between ob_start and ob_end_clean or ob_end_flush, you will get an error: ob_end_flush() failed to delete buffer zlib output compression

ini_set ( ‘zlib.output_compression’ , ‘1’ );

?>

ob_end_clean(); in this example will throw the error.

If there is no confidence about output buffering (enabled or not),
you may try these guards:

while ( ob_get_level () !== 0 ) ob_end_clean ();
>

while ( ob_get_length () !== false ) ob_end_clean ();
>

You might want to prevent your script from executing if the client already has the latest version.
You can do it like so:

$mtime=filemtime($_SERVER[«SCRIPT_FILENAME»])-date(«Z»);
$gmt_mtime = date(‘D, d M Y H:i:s’, $mtime) . ‘ GMT’;

if(isset($headers[«If-Modified-Since»])) if ($headers[«If-Modified-Since»] == $gmt_mtime) header(«HTTP/1.1 304 Not Modified»);
ob_end_clean();
exit;
>
>

$size=ob_get_length();
header(«Last-Modified: «.$gmt_mtime);
header(«Content-Length: $size»);
ob_end_flush();

Instead of checking the If-Modified-Since-Header against the date of the last modification of the script, you can of course query a database or take any other date that is somehow related to the modification of the result of your script.

You can for instance use this technique to generate images dynamically. If the user indicates he already has a version of the image by the If-Modified-Since-Header, there’s no need to generate it and let the server finally discard it because the server only then interpretes the If-Modified-Since-Header.
This saves server load and shortens response-times.

Читайте также:  Add dimension to array python

Keep in mind that mrfritz379’s example (#49800) is just an example. You can achieve that example’s result in a more efficient manner without using output buffering functions:

echo «

Search running. Please be patient. . .»;
$output = «

FileList:

\n»;
if (is_dir($dir)) $dh = opendir($dir);

while (($fd = readdir($dh)) != false) echo » .»;
$output .= $fd;
>
>
echo «
Search Complete!

\n»;
echo $output;

In addition to John Smith’s comment (#42939), ob_gzhandler() may still set the HTTP header «Content-Encoding» to «gzip» or «deflate» even if you call ob_end_clean(). This will cause a problem in the following situation:

1. Call ob_gzhandler().
2. Echo «Some content»;
3. Call ob_end_clean().
4. Echo «New content»;

In the above case, the browser may receive the «Content-Encoding: gzip» HTTP header and attempts to decompress the uncompressed «New content». The browser will fail.

In the following situation, this behaviour will go unnoticed:

1. Call ob_gzhandler().
2. Echo «Some content»;
3. Call ob_end_clean().
4. Call ob_gzhandler().
5. Echo «New content»;

This is because the second ob_gzhandler() will mask the absence of the first ob_gzhandler().

A solution would be to write a wrapper, like John Smith did, for the ob_gzhandler().

Источник

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.

Читайте также:  Json php запрос ответ

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 ();
?>

Источник

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