Backend Development
PHP Tutorial
Detailed explanation of output buffer control (Output Control) in PHPThis 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.

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();
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;
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 \ob_start();
php_info();
$v = ob_get_contents();
ob_end_clean();
echo $v;
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();
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;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();
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
The final output result is to replace apples content with oranges content.
Add URL rewriter
output_add_rewrite_var('var', 'value');
// some links
echo '<a href="file.php">link</a>
<a href="http://example.com">link2</a>';
// <a href="file.php?var=value">link</a>
// <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>
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
推荐学习:《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!
PHP's Purpose: Building Dynamic WebsitesApr 15, 2025 am 12:18 AMPHP is used to build dynamic websites, and its core functions include: 1. Generate dynamic content and generate web pages in real time by connecting with the database; 2. Process user interaction and form submissions, verify inputs and respond to operations; 3. Manage sessions and user authentication to provide a personalized experience; 4. Optimize performance and follow best practices to improve website efficiency and security.
PHP: Handling Databases and Server-Side LogicApr 15, 2025 am 12:15 AMPHP uses MySQLi and PDO extensions to interact in database operations and server-side logic processing, and processes server-side logic through functions such as session management. 1) Use MySQLi or PDO to connect to the database and execute SQL queries. 2) Handle HTTP requests and user status through session management and other functions. 3) Use transactions to ensure the atomicity of database operations. 4) Prevent SQL injection, use exception handling and closing connections for debugging. 5) Optimize performance through indexing and cache, write highly readable code and perform error handling.
How do you prevent SQL Injection in PHP? (Prepared statements, PDO)Apr 15, 2025 am 12:15 AMUsing preprocessing statements and PDO in PHP can effectively prevent SQL injection attacks. 1) Use PDO to connect to the database and set the error mode. 2) Create preprocessing statements through the prepare method and pass data using placeholders and execute methods. 3) Process query results and ensure the security and performance of the code.
PHP and Python: Code Examples and ComparisonApr 15, 2025 am 12:07 AMPHP and Python have their own advantages and disadvantages, and the choice depends on project needs and personal preferences. 1.PHP is suitable for rapid development and maintenance of large-scale web applications. 2. Python dominates the field of data science and machine learning.
PHP in Action: Real-World Examples and ApplicationsApr 14, 2025 am 12:19 AMPHP is widely used in e-commerce, content management systems and API development. 1) E-commerce: used for shopping cart function and payment processing. 2) Content management system: used for dynamic content generation and user management. 3) API development: used for RESTful API development and API security. Through performance optimization and best practices, the efficiency and maintainability of PHP applications are improved.
PHP: Creating Interactive Web Content with EaseApr 14, 2025 am 12:15 AMPHP makes it easy to create interactive web content. 1) Dynamically generate content by embedding HTML and display it in real time based on user input or database data. 2) Process form submission and generate dynamic output to ensure that htmlspecialchars is used to prevent XSS. 3) Use MySQL to create a user registration system, and use password_hash and preprocessing statements to enhance security. Mastering these techniques will improve the efficiency of web development.
PHP and Python: Comparing Two Popular Programming LanguagesApr 14, 2025 am 12:13 AMPHP and Python each have their own advantages, and choose according to project requirements. 1.PHP is suitable for web development, especially for rapid development and maintenance of websites. 2. Python is suitable for data science, machine learning and artificial intelligence, with concise syntax and suitable for beginners.
The Enduring Relevance of PHP: Is It Still Alive?Apr 14, 2025 am 12:12 AMPHP is still dynamic and still occupies an important position in the field of modern programming. 1) PHP's simplicity and powerful community support make it widely used in web development; 2) Its flexibility and stability make it outstanding in handling web forms, database operations and file processing; 3) PHP is constantly evolving and optimizing, suitable for beginners and experienced developers.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

AI Hentai Generator
Generate AI Hentai for free.

Hot Article

Hot Tools

Dreamweaver Mac version
Visual web development tools

SublimeText3 English version
Recommended: Win version, supports code prompts!

Notepad++7.3.1
Easy-to-use and free code editor

Atom editor mac version download
The most popular open source editor

SAP NetWeaver Server Adapter for Eclipse
Integrate Eclipse with SAP NetWeaver application server.






