PHP Tutorials - Herong's Tutorial Examples
Dr. Herong Yang, Version 3.00

ob_start() - Output Buffering Function

This section describes how to use the ob_start() function to turn on output buffering, which allows HTTP response header lines to be added after response body has been added.

As you can see from setcookie() definition, the PHP engine provides no buffer for the HTTP response body. That means as soon the PHP script starts to send output to the HTTP response body, the HTTP header block will be finalized, and not allowed to change any more.

But this default behavior can be altered by calling output control functions:

  • setcookie() must be called before any output to the HTTP response. The main reason is that PHP is not buffering the HTTP response. But you can alter this behavior by using ob_*() functions.
  • ob_start() - A built-in function that turns on output buffering.
  • flush() - A built-in function that flushes out the contents of the output buffer to the HTTP response body.

Of course, default behavior can also be altered by the configuration file, php.ini. Open php.ini and set the following line:

output_buffering = 4096

The above configuration line tells the PHP engine to turn on output buffering, and set the buffer size to 4096 bytes. Once "output_buffering" is turned on, you don't have to call ob_start() in your scripts.

To test the PHP engine default behavior, I modified CookieTest.php into CookieOutputBuffer.php:

<?php #CookieOutputBuffer.php
# Copyright (c) 2005 by Dr. Herong Yang, http://www.herongyang.com/
#
   print("<pre>\n");
   print("Adding cookies by the server:\n");

   $numCookies = count( array_keys($_COOKIE) );
   $numCookies++;
   $cookieName = "Cookie_$numCookies";
   $cookieValue = "My cookie value";
   print("   $cookieName: $cookieValue\n");

   setcookie($cookieName, $cookieValue);

   print("\nCookies received by the server:\n");
   foreach ($_COOKIE as $k => $v) {
      print "   $k = $v\n";
   }
   
   print "</pre>\n";
?>

I then opened php.ini and set the following line:

output_buffering = 0

Running IE on CookieOutputBuffer.php gave me this:

Adding cookies by the server:
   Cookie_2: My cookie value

Cookies received by the server:
   User = Herong Yang

PHP Warning: Cannot modify header information - headers already 
sent by (output started at ...\CookieOutputBuffer.php:4) ...

Now I truly beblieve that PHP engine's default behavior is no output buffering. Make sure to change "output_buffering" back to 4096 before continuing to the next test.

Last update: 2005.

Sections in This Chapter

What Is a Cookie?

Sending and Receiving Cookies

Sending and Receiving Cookies - Example

ob_start() - Output Buffering Function

Persistent Cookies Saved on Hard Disk

Other Cookie Properties - Domain and Path

Dr. Herong Yang, updated in 2009
ob_start() - Output Buffering Function