Home > Backend Development > PHP Tutorial > Detailed explanation of output buffer control (Output Control) in PHP

Detailed explanation of output buffer control (Output Control) in PHP

青灯夜游
Release: 2023-04-10 08:50:02
forward
3700 people have browsed it

This article will take you to understand the output buffer control (Output Control) in PHP. It has certain reference value. Friends in need can refer to it. I hope it will be helpful to everyone.

Detailed explanation of output buffer control (Output Control) in PHP

In PHP, when we directly echo or print_r, the output content will be printed directly. However, in some cases, we do not want to print directly. At this time, we can use the output buffer control to control the output printing. Of course, this set of functions is not limited to printing content, we can also perform other operations, which we will discuss at the end.

Clear output

First, let’s take a look at not allowing things like echo to print output.

ob_start();
echo 111, PHP_EOL;
echo "aaaa", PHP_EOL;
ob_end_clean();
Copy after login

I believe many friends should have seen the ob_start() function. Its function is to start a period of output buffer control. The output statements in the code after ob_start() will enter the output buffer. At this time, if we call ob_end_clean(), ob_clean() or ob_get_clean(), there will be no output. The function of all three of them is to clear the contents of the output buffer. For specific differences, you can refer to the function description or official documentation given at the end of the article.

Get 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 after login

As mentioned above, using ob_end_clean() will clear the contents of the output buffer, but in this code , we use the ob_get_contents() function to directly assign the contents of the buffer to the variable \v. At this time, v. At this time,

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

echo $v;
Copy after login
The content in $v is the content of php_info(). This is the second capability of output buffer control.

Refresh (output) buffer content

ob_start();
echo 111, PHP_EOL;
echo "aaaa", PHP_EOL;
flush();
ob_flush();
Copy after login
Similarly, if we want to directly output the content again in the buffer, use flush(), ob_flush(), Ob_end_flush() and ob_get_flush() are enough. In fact, it is equivalent to making the echo output statements after ob_start() revalidate and output normally.

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

ob_implicit_flush();

ob_start();
echo 111, PHP_EOL;
echo "aaaa", PHP_EOL;
Copy after login

After using ob_implicit_flush(), we no longer need to manually call functions such as ob_flush() to refresh the buffer content.

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 after login
ob_get_length() will return the length of the content in the current buffer. Here we only print a 123 and save 3 in the buffer. characters, so the output is exactly 3. ob_get_level() returns the level of the current buffer. Please note that we called ob_start() twice above, which means there are two levels of buffers. This buffer can be nested. The ob_get_status() function is the status information of the buffer. For field descriptions, you can view the official documentation and will not go into details here.

Use the callback function of ob_start() to replace the content of the output buffer

This is an example, but it can be extended to other functions. For example, we can use To perform global output filtering, compression and 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 after login

The final output result is to replace apples content with oranges content.

Add URL rewriter

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

// <a href="file.php?var=value">link</a>
// <a href="http://example.com">link2</a>

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

// <form action="script.php" method="post">
// <input type="hidden" name="var" value="value" />
// <input type="text" name="var2" />
// </form>
Copy after login
Do you see any clues in the above code? That's right, using the output_add_rewrite_var() function, we can add a parameter to the HTML link or form code when PHP outputs. Do you have any use scenarios in mind? Prevention of CSRF attacks on POST forms.

This function will be added according to the url_rewriter.tags configuration item in the php.ini file. By default, this configuration item only supports the from form. At the same time, it can also support the href and area tags of the a tag. href, frame tag's src, input tag's src, etc. That is, fields will be automatically added to the properties corresponding to these tags. Of course, it also has an inverse function output_reset_rewrite_vars() for canceling the previously added parameter.

总结

关于输出缓冲控制这块还有很多好玩的东西,不过限于篇幅我们先介绍到这里,将来踫到什么好的功能的应用我们再单独讲解。现在基于 Swoole 的应用越来越多,当我们需要将 TP 、 Laravel 这类传统框架转换成支持 Swoole 的时候,往往就需要在入口文件使用输出缓冲控制来进行修改。因为传统框架基本都是直接进行 echo 之类的输出的,而在 Swoole 中,echo 这类的内容是直接打印在控制台的,这就需要我们通过 ob_get_contents() 能力获得全部的输出再通过 response->end() 来进行实际的响应。另外,还有一些其他的场景也会用到输出缓冲控制:

  • 1.在PHP中,像header(), session_start(), setcookie() 等这样的发送头文件的函数前,不能有任何的输出,而利用输出缓冲控制函数可以在这些函数前进行输出而不报错
  • 2.对输出的内容进行处理,例如生成静态缓存文件、进行gzip压缩输出,这算是较常用的功能了
  • 3.捕获一些不可获取的函数输出,例如phpinfo(), var_dump() 等等,这些函数都会将运算结果显示在浏览器中,而如果我们想对这些结果进行处理,则用输出缓冲控制函数是个不错的方法。说的通俗点,就是这类函数都不会有返回值,而要获取这些函数的输出数据,就要用到输出缓冲控制函数
  • 4.对一些数据进行实时的输出

最后,再给出输出缓冲控制相关的函数说明,具体内容大家还是要多看官方文档的介绍。

  • 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_start中使用的用来压缩输出缓冲区中内容的回调函数。ob_start callback function to gzip output buffer
  • ob_implicit_flush — 打开/关闭绝对刷送
  • ob_list_handlers — 列出所有使用中的输出处理程序。
  • ob_start — 打开输出控制缓冲
  • output_add_rewrite_var — 添加URL重写器的值(Add URL rewriter values)
  • output_reset_rewrite_vars — 重设URL重写器的值(Reset URL rewriter values)
测试代码:
https://github.com/zhangyue0503/dev-blog/blob/master/php/202005/source/%E8%BF%98%E6%90%9E%E4%B8%8D%E6%87%82PHP%E4%B8%AD%E7%9A%84%E8%BE%93%E5%87%BA%E7%BC%93%E5%86%B2%E6%8E%A7%E5%88%B6%EF%BC%9F.php
Copy after login

推荐学习:《PHP视频教程

The above is the detailed content of Detailed explanation of output buffer control (Output Control) in PHP. For more information, please follow other related articles on the PHP Chinese website!

Related labels:
php
source:juejin.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template