Details of output_buffering in PHP

  • 2021-07-21 07:39:04
  • OfStack

Personally, I think Output buffering is a relatively pure 4.0 feature. Although quite simple in concept, output buffering is very powerful and makes it easier for developers to develop advanced and effective programs.

This article introduces HTTP header, how output buffering can help you with HTTP header, and introduces some advanced uses of output buffering.

HTTP Header

For each request established using the HTTP protocol, the response generated by the Web server typically consists of two parts: a header and a body. For example, if you have a small text file called example. txt in the document root directory of the Web server, the file contains the texts Hello, world! The response to the HTTP request for this file is as follows:


HTTP/1.1 200 OK
Date: Sat, 02 Sep 2000 21:40:08 GMT
Server: Apache/1.3.11 (Unix) mod_macro/1.1.1 PHP/4.0.2-dev
Last-Modified: Sat, 02 Sep 2000 21:39:49 GMT
ETag: "12600b-e-39b173a5"
Accept-Ranges: bytes
Content-Length: 14
Connection: close
Content-Type: text/plain
Hello, world!

The first part of this request (the more part) is HTTP header. Although the user cannot see HTTP header in the browser, it contains information for the browser, such as the document content type, the protocol version used, the date the document was last changed, and so on. HTTP header doesn't have a lot of rules, and it usually has the following format:


Field: Value[ Field: Value ]

They must be separated from the document body by empty lines.

You can add or change information for this HTTP header from the PHP script. For example, you can use the header () function:


header("Location: http://www.php.net/");     // Redirect to http://www.php.net/

You can also use the SetCookie () function:


SetCookie("foo", "bar");

You may know that HTTP cookies is implemented using HTTP headers. For example, the HTTP request response for the following PHP file


<?php
SetCookie("foo", "bar");
print "Set cookie.";
?>

It will be like this:


HTTP/1.1 200 OK
Date: Sat, 02 Sep 2000 21:43:02 GMT
Server: Apache/1.3.11 (Unix) mod_macro/1.1.1PHP/4.0.2-dev
X-Powered-By: PHP/4.0.2-dev
Set-Cookie: foo=bar
Connection: close
Content-Type: text/html
Set cookie.

The browser reads the HTTP header returned from the server and knows that an cookie called foo (in this case, an session cookie) has been sent, and its value is bar.

Why use Output Buffering technology

The need for output buffering technology was obvious as early as PHP/FI 2.0. If you have used this version of PHP, you may remember that you often encounter error messages such as Oops, SetCookie, called, after, header, has, been, sent, and you can't figure out why.

If you have used the latest version of PHP-PHP 3.0 or even PHP 4.0-you will know this error message: Oops, php_set_cookie called after header has been sent. Or, you will encounter an Cannot add header information-headers already sent message when you try to call the header () function of PHP. 1 In general, output buffering technology users avoid these annoying error messages, while developers can also use them for advanced purposes.

When did these mistakes occur? These error messages are generated if you try to add or modify header information after HTTP header has been sent, and if a blank line is missing between the document body and the header. To understand how this occurs, let's look at how PHP handles HTTP header output and body output.

When the script starts executing, it can send header (title) information and body information at the same time.

The Header information (from the header () or SetCookie () functions) is not sent immediately; Instead, it is saved to a list.

This allows you to modify the header information, including the default header (for example, Content-Type header). However, if the script sends any output that is not header (for example, using blocks or print () calls), PHP must send all headers first, then send blank lines, terminate HTTP header, and then continue to send body data after that. From this point on, any attempt to add or modify header information is not allowed, and one of the above error messages is sent.

While this does not cause much problem, sometimes it simply terminates HTTP header before any input is issued, complicating the script logic. Output buffering technology can solve these problems.

Working Principle of Output Buffering

When output buffering is enabled, PHP does not send HTTP header when the script sends output. Instead, it puts this output through a pipe (pipe) into a dynamically increased cache (used only in PHP 4.0, which has a centralized output mechanism). You can still modify, add header lines, or set cookie because headers are not actually sent. In the simplest case, when the script terminates, PHP will automatically send HTTP header to the browser, and then send the contents of the output buffer. It's simple.

Basic usage

You can use the following four functions to help you control output buffering:


ob_start()

Enable the output buffering mechanism.

Output buffering supports multiple levels--for example, the ob_start () function can be called multiple times.

ob_end_flush()

Send output buffer (output buffering) and disable the output buffering mechanism.

ob_end_clean()

Clear output buffer without sending, and disable output buffering.

ob_get_contents()

Returns the current output buffer as a string. Allows you to process any output from the script.

In addition, the output_buffering directive in php. ini can be enabled. If this directive is enabled, each PHP script starts with a call to the ob_start () function.

Example 1


<?php ob_start(); ?>
<h1>Example 1</h1>
<?php
print "Hello, $user ";
SetCookie("Wow", "This cookie has been set even though we've already emitted output!");
?>

Here, even though you have sent the output (in the HTML code block and in the print statement), you can use the SetCookie () call without error, thanks really to the output buffering mechanism. Note that using the output buffering mechanism for this purpose causes a certain degree of performance loss, so it is best not to enable this mechanism by default. However, for more complex scripts, output buffering simplifies the logic.

Example 2


<?php
ob_start();
print "Here's a pretty dumb way to calculate the length of a string.";
$length = strlen(ob_get_buffer());
ob_end_clean();
?>

This example shows an inefficient way to determine the length of a string. Instead of simply using the strlen () function, it first enables the output buffering mechanism, prints out the string, and then determines the length of output buffer. Finally, clear the output buffer (not sent), and then disable the output buffering mechanism.


Related articles: