search
HomeBackend DevelopmentPHP TutorialDetailed 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
bufferlinuxoutputphpuseMemoryaddressyesofspacesystembufferDetailed 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 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 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 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 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
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
PHP Performance Tuning for High Traffic WebsitesPHP Performance Tuning for High Traffic WebsitesMay 14, 2025 am 12:13 AM

ThesecrettokeepingaPHP-poweredwebsiterunningsmoothlyunderheavyloadinvolvesseveralkeystrategies:1)ImplementopcodecachingwithOPcachetoreducescriptexecutiontime,2)UsedatabasequerycachingwithRedistolessendatabaseload,3)LeverageCDNslikeCloudflareforservin

Dependency Injection in PHP: Code Examples for BeginnersDependency Injection in PHP: Code Examples for BeginnersMay 14, 2025 am 12:08 AM

You should care about DependencyInjection(DI) because it makes your code clearer and easier to maintain. 1) DI makes it more modular by decoupling classes, 2) improves the convenience of testing and code flexibility, 3) Use DI containers to manage complex dependencies, but pay attention to performance impact and circular dependencies, 4) The best practice is to rely on abstract interfaces to achieve loose coupling.

PHP Performance: is it possible to optimize the application?PHP Performance: is it possible to optimize the application?May 14, 2025 am 12:04 AM

Yes,optimizingaPHPapplicationispossibleandessential.1)ImplementcachingusingAPCutoreducedatabaseload.2)Optimizedatabaseswithindexing,efficientqueries,andconnectionpooling.3)Enhancecodewithbuilt-infunctions,avoidingglobalvariables,andusingopcodecaching

PHP Performance Optimization: The Ultimate GuidePHP Performance Optimization: The Ultimate GuideMay 14, 2025 am 12:02 AM

ThekeystrategiestosignificantlyboostPHPapplicationperformanceare:1)UseopcodecachinglikeOPcachetoreduceexecutiontime,2)Optimizedatabaseinteractionswithpreparedstatementsandproperindexing,3)ConfigurewebserverslikeNginxwithPHP-FPMforbetterperformance,4)

PHP Dependency Injection Container: A Quick StartPHP Dependency Injection Container: A Quick StartMay 13, 2025 am 12:11 AM

APHPDependencyInjectionContainerisatoolthatmanagesclassdependencies,enhancingcodemodularity,testability,andmaintainability.Itactsasacentralhubforcreatingandinjectingdependencies,thusreducingtightcouplingandeasingunittesting.

Dependency Injection vs. Service Locator in PHPDependency Injection vs. Service Locator in PHPMay 13, 2025 am 12:10 AM

Select DependencyInjection (DI) for large applications, ServiceLocator is suitable for small projects or prototypes. 1) DI improves the testability and modularity of the code through constructor injection. 2) ServiceLocator obtains services through center registration, which is convenient but may lead to an increase in code coupling.

PHP performance optimization strategies.PHP performance optimization strategies.May 13, 2025 am 12:06 AM

PHPapplicationscanbeoptimizedforspeedandefficiencyby:1)enablingopcacheinphp.ini,2)usingpreparedstatementswithPDOfordatabasequeries,3)replacingloopswitharray_filterandarray_mapfordataprocessing,4)configuringNginxasareverseproxy,5)implementingcachingwi

PHP Email Validation: Ensuring Emails Are Sent CorrectlyPHP Email Validation: Ensuring Emails Are Sent CorrectlyMay 13, 2025 am 12:06 AM

PHPemailvalidationinvolvesthreesteps:1)Formatvalidationusingregularexpressionstochecktheemailformat;2)DNSvalidationtoensurethedomainhasavalidMXrecord;3)SMTPvalidation,themostthoroughmethod,whichchecksifthemailboxexistsbyconnectingtotheSMTPserver.Impl

See all articles

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 Article

Hot Tools

MinGW - Minimalist GNU for Windows

MinGW - Minimalist GNU for Windows

This project is in the process of being migrated to osdn.net/projects/mingw, you can continue to follow us there. MinGW: A native Windows port of the GNU Compiler Collection (GCC), freely distributable import libraries and header files for building native Windows applications; includes extensions to the MSVC runtime to support C99 functionality. All MinGW software can run on 64-bit Windows platforms.

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

DVWA

DVWA

Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

PhpStorm Mac version

PhpStorm Mac version

The latest (2018.2.1) professional PHP integrated development tool