M
M
Maxim Ivanov2015-09-29 22:38:01
PHP
Maxim Ivanov, 2015-09-29 22:38:01

Can you explain why buffering is useful?

function display(){/* работа шаблонизатора, замена меток */}
ob_start(display);
  require 'template/index.html';
ob_end_flush();

I saw this code, and I can't understand how this ob_start is useful.
In the documentation, as elsewhere, they simply write:
This function enables output buffering. If output buffering is active, script output is not sent (except headers), but stored in an internal buffer.

Answer the question

In order to leave comments, you need to log in

3 answer(s)
D
Denis, 2015-09-29
@omaxphp

Once upon a time, php did not use a buffer and sent everything to the client at once.
Roughly like this

<?php

for ($i = 1; $i <= 100; $i++) {
    echo $i;
    ob_flush();
    flush();

    usleep(300000);
}
ob_end_flush();

The buffer is now enabled by default.
And it looks like this. ( Sergey Protko already said this )
<?php

$buffer = '';
for ($i = 1; $i <= 100; $i++) {
    $buffer .= $i;
    if (strlen($buffer) > 50) {
        echo $buffer;
        $buffer = '';
    }
}
echo $buffer;

But apart from the headers already mentioned...
The buffer can be controlled.
For example. We have an error in the included template.
Without a buffer, puff will gladly give it to the client and die halfway through.
With a buffer, we can "ignore" it or change the contents altogether.
As a result, on the page where we have the menu, it will not show off "PHP Notice ....",
but the human text "An error has occurred" or even an empty space.
<?php

error_reporting(E_ALL);
ini_set('display_errors', 1);

$buffer = '';

function handler($ouputBuffer) {
    global $buffer;
    $buffer = $ouputBuffer;
}

ob_start('handler');
$ChuckNorris = 5 / 0;
ob_end_flush();

// Клиенту не полетит E_WARNING
echo "E_WARNING"; 

echo "<pre>";
var_dump($buffer);
echo "</pre>";
exit("File: " . __FILE__ . " Line: " . __LINE__);

In any case, this is a useful thing and you need to understand it at least a little, but understand it.

P
Pavel Volintsev, 2015-09-29
@copist

Ensure that the HTTP headers are sent before the content.

A
Alexander Taratin, 2015-09-29
@Taraflex

You can intercept and modify the output of a script written by another developer in order to perform additional manipulations on this output or completely clear it.

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question