One of the discussions about output buffer (Outputbuffering)

Source: Internet
Author: User
######################################## ### Title about output buffering ## organize diegolympus @ Lin ## original ByZeevSuraski #################### #################### Outputbuffering) why does the directory HTTPHeader use OutputBuffering technology Out ################################ #########
# Title about output buffering
# Sort out Diego Lynn @ Lin nationwide
# Original file By Zeev Suraski
######################################## #

Output buffering)

Directory

HTTP Header
Why use Output Buffering technology?
How Output Buffering works
Basic usage
Advanced usage
Make things easier
Haha, I succeeded.

I personally think that Output buffering is a pure 4.0 Feature of PHP. Although the concept is quite simple, the output buffering function is very powerful, making it easier for developers to develop advanced and effective programs.

This article describes HTTP headers, how output buffering helps you process HTTP headers, and some advanced usage of output buffering.

HTTP Header [HTTP title]
For each request created using the HTTP protocol, the response generated by the Web server usually consists of two parts: the title and the subject. For example, if there is a small file named example.txt in the webserver file root directory, the file contains the text Hello, world !, The HTTP request response to 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 (that is, a large part) is the HTTP header. Although the user does not see the HTTP header in the browser, it contains information for the browser, such as the document content type, the protocol version used, the last modification date of the document, and so on. HTTP header does not have many rules. generally, its format is as follows:

Field: Value [Field: Value]
They must be separated from the document subject using blank lines.

You can add or modify the HTTP header information from a 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 are implemented using HTTP headers. For example, the following php file's HTTP request response


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.1 PHP/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 sends a cookie named foo (here it is a session cookie). its value is bar.

Why use Output Buffering technology?

As early as PHP/FI 2.0, output buffering technology was obviously needed. If you have used this version of PHP, you may still remember to frequently encounter the Oops, SetCookie called after header has been sent error message, and cause your ears to be caught, the reason is also unclear.

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

When did these errors occur? If you try to add or modify the title information after the HTTP header has been sent, and there is no blank line between the document subject and the title, these error messages will be generated. To understand how this is generated, let's take a look at how PHP handles HTTP header output and body output.

When the script starts to be executed, it can send both header and subject information. Header information (from header () or SetCookie () function) is not sent immediately. Instead, it is saved to a list. This allows you to modify the title information, including the default title (for example, Content-Type title ). However, once the script sends any output without a title (for example, called using an HTML code block or print (), PHP must first send all headers and then send empty lines, terminate the HTTP header before sending the body data. At this time, any attempt to add or modify the title information is not allowed, and one of the above error messages will be sent.

Although this does not cause much problems, sometimes it is only necessary to terminate the HTTP header before any input is sent, which may complicate the script logic. Output buffering technology can solve these problems.

How Output Buffering works
When output buffering is enabled, PHP does not send HTTP headers when the script sends the output. Instead, it inputs this output to the dynamically added cache through the pipeline (pipe) (which can only be used in PHP 4.0 and has a centralized output mechanism ). You can still modify, add the title line, or set the cookie because the title is not actually sent. The simplest case is that when the script is terminated, PHP will automatically send the HTTP header to the browser and then send the content in the output buffer. This is 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, you can call the ob_start () function multiple times.

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

Ob_end_clean ()
Clear the output buffer but not send it, 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, you can enable the output_buffering command in php. ini. If this command is enabled, every PHP script calls the ob_start () function at the beginning.

Example 1



Example 1


Print "Hello, $ user \ n ";

SetCookie ("Wow", "This cookie has been set even though we 've already emitted output! ");

?>
Here, although you have sent the output (in the HTML code block and print statement), you can also use SetCookie () to call it without errors. thanks to the output buffering mechanism. Please note that using the output buffering mechanism for this purpose will cause a certain degree of performance loss, so it is best not to enable this mechanism by default. However, for complex scripts, output buffering can simplify logic.

Example 2

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 inefficient method for determining the string length. Instead of simply using the strlen () function, it first starts the output buffering mechanism, prints the string, and then determines the length of the output buffer. Finally, clear the output buffer (not sent) and 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.