Home Backend Development PHP Tutorial Detailed explanation of the use of php buffer output_buffering_PHP tutorial

Detailed explanation of the use of php buffer output_buffering_PHP tutorial

Jul 21, 2016 pm 03:07 PM
buffer linux output php use Memory address yes of space system buffer Detailed explanation

buffer
buffer is a memory address space. The default size of the Linux system is generally 4096 (4kb), which is one memory page. It is mainly used to store data transfer areas between devices with unsynchronized speeds or devices with different priorities. Through the buffer, the processes can wait less for each other. Here is a more general example. When you open a text editor to edit a file, every time you enter a character, the operating system will not immediately write the character directly to the disk, but first write it to the buffer. When writing When a buffer is full, the data in the buffer will be written to the disk. Of course, when the kernel function flush() is called, it is mandatory to write the dirty data in the buffer back to the disk.

Similarly, when echo and print are executed, the output is not immediately transmitted to the client browser for display through tcp, but the data is written to the php buffer. The php output_buffering mechanism means that a new queue is established before the tcp buffer, and data must pass through the queue. When a php buffer is full, the script process will hand over the output data in the php buffer to the system kernel and pass it to the browser via TCP for display. Therefore, the data will be written to these places in sequence: echo/print -> php buffer -> tcp buffer -> browser

php output_buffering
By default, php buffer is turned on, and the default value of the buffer is 4096, which is 4kb. You can find the output_buffering configuration in the php.ini configuration file. When echo, print, etc. output user data, the output data will be written to php output_buffering. Until output_buffering is full, the data will be sent to the browser through tcp. show. You can also manually activate the php output_buffering mechanism through ob_start(), so that even if the output exceeds 4kb of data, the data is not actually handed over to tcp and passed to the browser, because ob_start() sets the php buffer space to be large enough. The data will not be sent to the client browser until the end of the script or the ob_end_flush function is called.

1. When output_buffering=4096, and output less data (less than one buffer)

Copy code The code is as follows:

for ($i = 0; $i < 10; $i++) {
echo $i . '
';
sleep($i + 1); //
}
?>

Phenomenon: There is not intermittent output every few seconds, but until the response ends , you can see the output at once. The browser interface remains blank until the server script processing is completed. This is because the amount of data is too small and php output_buffering is not full. The order of writing data is echo->php buffer->tcp buffer->browser

2. When output_buffering=0, and output less data (less than one buffer)

Copy code The code is as follows:

//Passing ini_set('output_buffering', 0) does not take effect
//You should edit /etc/php.ini and set output_buffering=0 to disable output buffering mechanism
//ini_set('output_buffering', 0); //Completely disable the output buffering function
for ($i = 0; $i < 10; $i++) {
echo $i . '
';
flush(); //Notify the bottom layer of the operating system and send the data to the client browser as soon as possible
sleep($i + 1); //
}
?>

Phenomenon: It is not consistent with what was shown just now. After disabling the php buffering mechanism, you can see intermittent output in the browser, and you do not have to wait until the script is executed to see the output. This is because, the data does not stay in php output_buffering. The order of writing data is echo->tcp buffer->browser

3. When output_buffering=4096., the output data is larger than one buffer, ob_start() is not called

Copy code The code is as follows :

#//Create a 4kb file
$dd if=/dev/zero of=f4096 bs=4096 count=1
for ($i = 0; $i < 10; $i++) {
echo file_get_contents('./f4096') . $i . '
';
sleep($i +1 ; . Although the php output_buffering mechanism is enabled, there is still intermittent output instead of one-time output because the output_buffering space is not enough. Every time a php buffering is filled, the data will be sent to the client browser.


4. When output_buffering=4096, the output data is larger than one tcp buffer, call ob_start()

Copy code
The code is as follows:


ob_start(); //Open php buffer
for ($i = 0; $i < 10; $i++) {
echo file_get_contents('. /f4096') . $i . '
';
sleep($i + 1);
}
ob_end_flush();
?>

Phenomenon: You don’t see complete output until the server-side script processing is completed and the response ends. The output interval is so short that you can’t feel the pause. Before output, the browser maintains a blank interface, waiting for server data. This is because once PHP calls the ob_start() function, it will expand the PHP buffer to a large enough size. The data in the PHP buffer will not be sent to the client browser until the ob_end_flush function is called or the script ends.

output buffering function

1.ob_get_level
Returns the nesting level of the output buffering mechanism, can prevent repeated nesting of templates Set yourself up.

1.ob_start
Activate the output_buffering mechanism. Once activated, the script output is no longer sent directly to the browser, but is temporarily written to the PHP buffer memory area.

php enables the output_buffering mechanism by default, but by calling the ob_start() function, the data output_buffering value is expanded to a large enough value. You can also specify $chunk_size to specify the value of output_buffering. The default value of $chunk_size is 0, which means that the data in the php buffer will not be sent to the browser until the end of the script. If you set the size of $chunk_size, it means that as long as the data length in the buffer reaches this value, the data in the buffer will be sent to the browser.

Of course, you can process the data in the buffer by specifying $ouput_callback. For example, the function ob_gzhandler compresses the data in the buffer and then sends it to the browser.

2.ob_get_contents
Get a copy of the data in the php buffer. It is worth noting that you should call this function before the ob_end_clean() function call, otherwise ob_get_contents() returns a null character.

3. ob_end_flush and ob_end_clean
These two functions are somewhat similar, both will turn off the ouptu_buffering mechanism. But the difference is that ob_end_flush only flushes (flush/send) the data in the php buffer to the client browser, while ob_clean_clean clears (erase) the data in the php bufeer but does not send it to the client browser. After ob_end_flush is called, the data in the php buffer still exists, and ob_get_contents() can still obtain a copy of the data in the php buffer. After calling ob_end_clean(), ob_get_contents() gets an empty string, and the browser cannot receive the output, that is, there is no output.

Usage cases
Ob_start() is often seen used in some template engines and page file caches. The program code for loading templates in wet CI below:

Copy the code The code is as follows:

  /*
   * Buffer the output
   *
   * We buffer the output for two reasons:
   * 1. Speed. You get a significant speed boost.
   * 2. So that the final rendered template can be
   * post-processed by the output class.  Why do we
   * need post processing?  For one thing, in order to
   * show the elapsed page load time.  Unless we
   * can intercept the content right before it's sent to
   * the browser and then stop the timer it won't be accurate.
   */
  ob_start();
  // If the PHP installation does not support short tags we'll
  // do a little string replacement, changing the short tags
  // to standard PHP echo statements.
  if ((bool) @ini_get('short_open_tag') === FALSE AND config_item('rewrite_short_tags') == TRUE)
  {
                        //替换短标记
   echo eval('?>'.preg_replace("/;*s*?>/", "; ?>", str_replace('  }
  else
  {
   include($_ci_path); // include() vs include_once() allows for multiple views with the same name
  }

                //记录调试信息
  log_message('debug', 'File loaded: '.$_ci_path);
  // Return the file data if requested
  if ($_ci_return === TRUE)
  {
   $buffer = ob_get_contents();
   @ob_end_clean();
   return $buffer;
  }
  /*
   * Flush the buffer... or buff the flusher?
   *
   * In order to permit views to be nested within
   * other views, we need to flush the content back out whenever
   * we are beyond the first level of output buffering so that
   * it can be seen and included properly by the first included
   * template and any subsequent ones. Oy!
   *
   */
  if (ob_get_level() > $this->_ci_ob_level + 1)
  {
   ob_end_flush();
  }
  else
  {
                        //将模板内容添加到输出流中
   $_ci_CI->output->append_output(ob_get_contents());
                        //清除buffer
   @ob_end_clean();
  }

www.bkjia.comtruehttp://www.bkjia.com/PHPjc/327578.htmlTechArticlebuffer buffer是一个内存地址空间,Linux系统默认大小一般为4096(4kb),即一个内存页。主要用于存储速度不同步的设备或者优先级不同的设备之间...
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

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

Video Face Swap

Video Face Swap

Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

PHP and Python: Different Paradigms Explained PHP and Python: Different Paradigms Explained Apr 18, 2025 am 12:26 AM

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Why Use PHP? Advantages and Benefits Explained Why Use PHP? Advantages and Benefits Explained Apr 16, 2025 am 12:16 AM

The core benefits of PHP include ease of learning, strong web development support, rich libraries and frameworks, high performance and scalability, cross-platform compatibility, and cost-effectiveness. 1) Easy to learn and use, suitable for beginners; 2) Good integration with web servers and supports multiple databases; 3) Have powerful frameworks such as Laravel; 4) High performance can be achieved through optimization; 5) Support multiple operating systems; 6) Open source to reduce development costs.

Choosing Between PHP and Python: A Guide Choosing Between PHP and Python: A Guide Apr 18, 2025 am 12:24 AM

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

PHP: An Introduction to the Server-Side Scripting Language PHP: An Introduction to the Server-Side Scripting Language Apr 16, 2025 am 12:18 AM

PHP is a server-side scripting language used for dynamic web development and server-side applications. 1.PHP is an interpreted language that does not require compilation and is suitable for rapid development. 2. PHP code is embedded in HTML, making it easy to develop web pages. 3. PHP processes server-side logic, generates HTML output, and supports user interaction and data processing. 4. PHP can interact with the database, process form submission, and execute server-side tasks.

PHP vs. Python: Use Cases and Applications PHP vs. Python: Use Cases and Applications Apr 17, 2025 am 12:23 AM

PHP is suitable for web development and content management systems, and Python is suitable for data science, machine learning and automation scripts. 1.PHP performs well in building fast and scalable websites and applications and is commonly used in CMS such as WordPress. 2. Python has performed outstandingly in the fields of data science and machine learning, with rich libraries such as NumPy and TensorFlow.

PHP and the Web: Exploring its Long-Term Impact PHP and the Web: Exploring its Long-Term Impact Apr 16, 2025 am 12:17 AM

PHP has shaped the network over the past few decades and will continue to play an important role in web development. 1) PHP originated in 1994 and has become the first choice for developers due to its ease of use and seamless integration with MySQL. 2) Its core functions include generating dynamic content and integrating with the database, allowing the website to be updated in real time and displayed in personalized manner. 3) The wide application and ecosystem of PHP have driven its long-term impact, but it also faces version updates and security challenges. 4) Performance improvements in recent years, such as the release of PHP7, enable it to compete with modern languages. 5) In the future, PHP needs to deal with new challenges such as containerization and microservices, but its flexibility and active community make it adaptable.

PHP and Python: A Deep Dive into Their History PHP and Python: A Deep Dive into Their History Apr 18, 2025 am 12:25 AM

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

How to run java code in notepad How to run java code in notepad Apr 16, 2025 pm 07:39 PM

Although Notepad cannot run Java code directly, it can be achieved by using other tools: using the command line compiler (javac) to generate a bytecode file (filename.class). Use the Java interpreter (java) to interpret bytecode, execute the code, and output the result.

See all articles