Output_buffering in PHP: outputbuffering_PHP tutorial

Source: Internet
Author: User
Tags set cookie
For more information about output_buffering in PHP, see outputbuffering. In PHP, output_buffering is described in detail. in my opinion, outputbuffering is a pure 4.0 Feature. Although the concept is quite simple, outputbuffering in outputbufferin PHP is described in detail, outputbuffering

I personally think that Output buffering is a pure 4.0 Feature. 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

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:

The code 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:

The code 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:

The code is as follows:


Header ("Location: http://www.php.net/"); // redirect to http://www.php.net/

You can also use the SetCookie () function:

The code is as follows:


SetCookie ("foo", "bar ");

You may know that HTTP cookies are implemented using HTTP headers. For example, the following php file's HTTP request response

The code is as follows:


<? Php
SetCookie ("foo", "bar ");
Print "Set cookie .";
?>

It will be like this:

The code is as follows:


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

Why use Output Buffering technology?

The output buffering technology was obviously needed in PHP/FI 2.0. 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 a block or print (), PHP must first send all the 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:

The code is as follows:


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

The code is as follows:


<? Php ob_start ();?>
Example 1
<? 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 the HTML block and print statement), you can also use SetCookie () to call it without making any error. 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

The code is 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 inefficient determination of 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.


How to enable output_buffering in PHP?

In PHP. INI, you can set the following parameters related to the output buffer:
Default name range correction record
Output_buffering "0" PHP_INI_PERDIR
Output_handler NULL PHP_INI_PERDIR available from PHP 4.0.4
Implicit_flush "0" PHP_INI_ALL is PHP_INI_PERDIR in PHP <= 4.2.3

A simple explanation is as follows:
Output_buffering boolean/integer
When this option is set to On, output control is used in all scripts. To limit the maximum value of the output buffer, set this option to the specified maximum number of bytes (for example, output_buffering = 4096 ). Starting with PHP 4.3.5, this option is always Off in the PHP-CLI.

Output_handler string
This option redirects all the output of the script to a function. For example, when output_handler is set to mb_output_handler (), the character encoding is changed to the specified encoding. Any processing function set will automatically process the output buffer.

Note: you cannot use both mb_output_handler () and ob_iconv_handler (), or ob_gzhandler () and zlib. output_compression.

Note: Only built-in functions can use this command. For user-defined functions, use ob_start ().

Implicit_flush boolean
The default value is FALSE. If this option is changed to TRUE, PHP will make the output layer automatically refresh after each segment of information block is output. This is equivalent to calling the flush () function in PHP after each use of functions such as print () and echo () or each HTML block.

When PHP is not used in the web environment, enabling this option has a serious impact on the performance of program execution. it is generally only recommended for debugging. In the invocation mode of cli sapi, the flag is set to TRUE by default.

See ob_implicit_flush ().

It will certainly be useful unless you modify the PHP. the INI location is not used by the system, for example, C: \ WINDOWS \ PHP. INI, of course, can be set elsewhere. In addition, the console program is not buffered.

In addition, you can Control the Output buffer in the program. for details, refer to the "CXIV. Output Control function" chapter in the manual. The main functions are as follows:

Flush -- refresh the output buffer
Ob_clean -- Clean (erase) the output buffer
Ob_end_clean -- Clean (erase) the output buffer and turn off output buffering
Ob_end_flush -- Flush (send) the output buffer and turn off output buffering
Ob_flush -- Flush (send) the output buffer
Ob_get_clean -- Get current buffer contents and delete current output buffer
Ob_get_contents -- Return the contents of the output buffer
Ob_get_flu ...... remaining full text>

The output_buffering option in the php configuration file

No.
This only controls the page content output. when it is opened, the page content is first saved in the buffer zone. after the page is executed, it is sent to the browser for display. when it is closed, the page content is directly sent to the browser for display.

This option can also be a numeric value, such as 4096, which means to send the content to the browser when the buffer content reaches 4096 bytes (or the execution is completed.

In my opinion, Output buffering is a pure 4.0 Feature. Although it seems quite simple in concept, output bufferin...

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.