Output_buffering in PHP details _php tips

Source: Internet
Author: User
Tags php script set cookie setcookie

I personally think that Output buffering is a relatively pure 4.0 characteristics. Although conceptually simple, the output buffering feature is powerful enough to make it easier for developers to develop advanced and efficient programs.

This article describes the HTTP header and how output buffering can help you handle HTTP headers, and introduces some of the advanced uses of output buffering.

HTTP Header

For each request that is established using the HTTP protocol, the response from the Web server typically consists of two parts-the title and the body. For example, if there is a small text file in the document root of the Web server, called Example.txt, and the file contains the text Hello, world!, the HTTP request response to this file is as follows:

Copy Code code as follows:

http/1.1 OK
Date:sat, Sep 21:40:08 GMT
server:apache/1.3.11 (Unix) mod_macro/1.1.1 Php/4.0.2-dev
Last-modified:sat, Sep 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 the request (that is, the larger part) is the HTTP header. Although the HTTP header is not visible to the user 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. The HTTP header does not have too many rules, and typically it has the following format:

Copy Code code as follows:

field:value[field: value]

They must be separated from the document body with empty rows.

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

Copy Code code as follows:

Header ("location:http://www.php.net/"); Redirect to http://www.php.net/

You can also use the Setcookie () function:

Copy Code code as follows:

Setcookie ("foo", "Bar");

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

Copy Code code as follows:

<?php
Setcookie ("foo", "Bar");
Print "Set cookie.";
?>

Will be like this:

Copy Code code as follows:

http/1.1 OK
Date:sat, Sep 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 a cookie called foo (here is a session cookie) is sent, and its value is bar.

Why to use output buffering technology

As early as PHP/FI 2.0, it was clear that the output buffering technology was needed. If you have used this version of PHP, you may also remember that you often encounter Oops, Setcookie called after header has been sent this error message, and let you take the head scratching ears, also confused what is the reason.

If you have used the latest PHP version-PHP 3.0 or even PHP 4.0-then you will know the error message: Oops, Php_set_cookie called after header has been sent. Alternatively, you will encounter the cannot add header information-headers already sent message when you try to invoke the header () function of PHP. In general, output buffering technology users to avoid these annoying error messages, while developers can also be used for advanced purposes.

When did these mistakes occur? These error messages are generated if you attempt to add or modify header information after you have sent an HTTP header, and when empty rows are missing between the document body and the caption. To understand how this is generated, let's look at how PHP handles HTTP header output and body output.

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

Header information (from the header () or Setcookie () function) is not sent immediately, instead, it is saved to a list.

This allows you to modify the header information, including the default headings (such as content-type headings). However, once the script sends any non-caption output (for example, using block or print () calls), then PHP must send all the headers and then send out a blank line, terminating the HTTP header before continuing to send the principal data. From this point on, any attempt to add or modify header information is disallowed and sends one of the above error messages.

While this does not cause much of a problem, sometimes it is just a matter of terminating the HTTP header before any input is made, causing the complexity of the scripting logic. Output buffering technology can solve these problems.

Operating principle of Output buffering

When you enable output buffering, PHP does not send an HTTP header when the script sends out outputs. Instead, it enters the output through the pipeline (pipe) into the dynamically incremented cache (which can only be used in PHP 4.0, which has a centralized output mechanism). You can still modify, add header rows, or set cookies because the title is not actually sent. In the simplest case, when the script terminates, PHP automatically sends the HTTP header to the browser and then sends the contents of the output buffer. It's easy.

Basic usage

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

Copy Code code as follows:

Ob_start ()

Enable the output buffering mechanism.

Output Buffering supports multiple tiers-for example, the Ob_start () function can be called multiple times.

Ob_end_flush ()

Sends output buffer (output buffering) and disables the output buffering mechanism.

Ob_end_clean ()

Clears output buffer but does not send, and disables output buffering.

Ob_get_contents ()

Returns the current output buffer to a string. Allows you to process any output that the script emits.

In addition, you can enable the Output_buffering directive in php.ini. If this directive is enabled, each PHP script is equivalent to calling the Ob_start () function at the beginning.

Example 1

Copy Code code as follows:

<?php Ob_start ();?>
<?php
Print "Hello, $user";
Setcookie ("Wow", "This cookie has been set even though we ' ve already emitted output!");
?>

Here, although you have sent the output (in both the HTML code block and the print statement), you can also use Setcookie () calls without error, thanks to the output buffering mechanism. Note that using the output buffering mechanism for this purpose can cause a certain level of performance loss, so it is best to not enable this mechanism by default. However, for complex scripts, output buffering can simplify logic.

Example 2

Copy Code code as follows:

<?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 a very low efficiency in determining the length of a string. Instead of simply using the strlen () function, it first enables the output buffering mechanism, prints the string, and then determines the length of the output buffer. Finally clear output buffer (not sent), and then disable the output buffering mechanism.

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.