In PHP, when we do echo, or print_r, the output is printed directly. However, in cases where we do not want to print directly, we can use the output buffer control to control the output print. Of course, this set of functions is not limited to printed content, and there are other operations that we can do, which we’ll talk about at the end.

Removal of the output

First, let’s look at not printing things like echo.

ob_start();
echo 111, PHP_EOL;
echo "aaaa", PHP_EOL;
ob_end_clean();
Copy the code

Ob_start () is a function that starts an output buffer. Output statements in the code after ob_start() go into the output buffer, and if we call ob_end_clean(), ob_clean(), or ob_get_clean(), there will be no output. All three are used to clear the contents of the output buffer. You can refer to the function description or official documentation at the end of the article for specific differences.

Gets the contents of the output buffer

ob_start();
echo 111, PHP_EOL;
echo "aaaa", PHP_EOL;
$v = ob_get_contents();
ob_end_clean();

echo $v;
Copy the code

As mentioned above, using ob_end_clean() would clean up the contents of the output buffer, but in this code, we use ob_get_contents() to directly assign the contents of the buffer to the variable \ v. At this point, V. At this point, V. In this case, v has what was in the previous two echo paragraphs, that is to say, in this set of operations we have what we should have printed, and we store it in a variable. What’s the use of that? We can get things like phpInfo () and var_dump() that output directly to functions and are not printed on the client screen. Such as:

ob_start();
php_info();
$v = ob_get_contents();
ob_end_clean();

echo $v;
Copy the code

The contents in $v are the contents of php_info(). This is the second ability of output buffering control.

Flushes (outputs) the contents of the buffer

ob_start();
echo 111, PHP_EOL;
echo "aaaa", PHP_EOL;
flush();
ob_flush();
Copy the code

Similarly, if we want to print directly again in the buffer, use flush(), ob_flush(), ob_end_flush(), and ob_get_flush(). This is the equivalent of reactivating output statements such as echo after ob_start().

In addition, we can use a function to automatically refresh.

ob_implicit_flush();

ob_start();
echo 111, PHP_EOL;
echo "aaaa", PHP_EOL;
Copy the code

With ob_implICIT_Flush (), we don’t need to manually call a function like ob_flush() to flush the contents of the buffer.

Some detection functions

ob_start();
ob_start();

echo 123, PHP_EOL;

echo ob_get_length(), PHP_EOL;
/ / 3

echo ob_get_level(), PHP_EOL;
/ / 2

print_r(ob_get_status(true));

// Array
/ / (
// [0] => Array
/ / (
// [name] => default output handler
// [type] => 0
// [flags] => 112
// [level] => 0
// [chunk_size] => 0
// [buffer_size] => 16384
// [buffer_used] => 0
/ /)

// [1] => Array
/ / (
// [name] => default output handler
// [type] => 0
// [flags] => 112
// [level] => 1
// [chunk_size] => 0
// [buffer_size] => 16384
// [buffer_used] => 17
/ /)

// )

ob_get_flush();
Copy the code

Ob_get_length () returns the length of the current buffer. In this case, we only printed a 123, and we saved three characters in the buffer, so the output is 3. Ob_get_level () returns the level of the current buffer. Note that we called ob_start() twice above, which means that there are two levels of the buffer, which can be nested. The ob_get_status() function is the buffer status information. The field description can be viewed in the official documentation.

The contents of the output buffer are replaced using the callback function of ob_start()

This is an example, but it can be generalized to other functions, such as global output filtering, compression optimization of CSS or JS files, etc.

ob_start(function($text){
    return (str_replace("apples"."oranges".$text));
});

echo "It's like comparing apples to oranges", PHP_EOL;
ob_get_flush();

// It's like comparing oranges to oranges
Copy the code

The result is that the apples content is replaced by the oranges content.

Add URL overrides

output_add_rewrite_var('var'.'value');
// some links
echo '<a href="file.php">link</a>
<a href="http://example.com">link2</a>';

// link
// <a href="http://example.com">link2</a>

// a form
echo '<form action="script.php" method="post">
<input type="text" name="var2" />
</form>';

// <form action="script.php" method="post">
// <input type="hidden" name="var" value="value" />
// <input type="text" name="var2" />
// </form>
Copy the code

What do you see in the code above? Yes, using the output_add_rewrite_var() function, we can add an argument to the HTML link or form code on the output of PHP. Do you have any usage scenarios in mind? Defense against CSRF attacks of the POST form.

This function is added according to the url_rewriter.tags configuration item in the php.ini file, which by default only supports the from form. It also supports href for a tag, href for area tag, SRC for frame tag, SRC for input tag, and so on. That is, fields are automatically added to the attributes corresponding to these tags. Of course, it also has an inverse function output_reset_rewrite_vars() to cancel the argument that was added earlier.

conclusion

There are a lot of interesting things to do with output buffering, but we’re going to stop there for the sake of space, and then we’ll talk about the finer features in the future. Nowadays, there are more and more Swoole-based applications, and when we need to convert traditional frameworks such as TP and Laravel to support Swoole, we often need to use output buffer control to modify the entry file. Because in traditional frameworks, you basically do echo and stuff like that, whereas in Swoole, echo and stuff like that is printed directly to the console, This requires us to obtain all the output through the ob_get_contents() capability and then make the actual response through response->end(). In addition, there are several other scenarios that use output buffering control:

  • 1. In PHP, functions such as header(), session_start(), setcookie(), etc. that send header files should not have any output before them. The output buffer control function can be used to output before these functions without error
  • 2. Process the output content, such as generating static cache files and gZIP compression output, which is a common function
  • 3. Capture the output of unretrievable functions such as phpinfo(), var_dump(), etc., which display the results in the browser. If we want to process the results, it is a good idea to use the output buffer control function. Generally speaking, none of these functions have a return value, and to retrieve the output of these functions, the output buffer control function is used
  • 4. Output some data in real time

Finally, the output buffer control related to the function description, the specific content we still want to see more official documentation.

  • Flush – Flushes the output buffer
  • Ob_clean – To clear (erase) the output buffer
  • Ob_end_clean – Empty (erase) the buffer and turn off the output buffer
  • Ob_end_flush – Flushes out (sends out) the contents of the output buffer and closes the buffer
  • Ob_flush – Flush out (send out) the contents of the output buffer
  • Ob_get_clean – Gets the contents of the current buffer and removes the current output cache.
  • Ob_get_contents – Returns the contents of the output buffer
  • Ob_get_flush – Spawns (sends out) the contents of the buffer, returns the contents as a string, and closes the output buffer.
  • Ob_get_length – Returns the length of the contents of the output buffer
  • Ob_get_level – Returns the nesting level of the output buffering mechanism
  • Ob_get_status – Gets the status of all output buffers
  • Ob_gzhandler – callback function used in ob_start to compress the contents of the output buffer. ob_start callback function to gzip output buffer
  • Ob_implicit_flush – Turns absolute flush on/off
  • Ob_list_handlers – Lists all output handlers in use.
  • Ob_start – Turns on output control buffering
  • Output_add_rewrite_var – Add URL rewriter values (Add URL rewriter values)
  • Output_reset_rewrite_vars – Reset URL rewriter values

Test code:

Github.com/zhangyue050…

Reference documents:

www.php.net/manual/zh/r…

www.php.net/manual/zh/s…

Blog.csdn.net/xiaofan1988…