search for in the  
<ob_list_handlersoutput_add_rewrite_var>
Last updated: Thu, 19 May 2005

ob_start

(PHP 4, PHP 5)

ob_start -- Turn on output buffering

Description

bool ob_start ( [callback output_callback [, int chunk_size [, bool erase]]] )

This function will turn output buffering on. While output buffering is active no output is sent from the script (other than headers), instead the output is stored in an internal buffer.

The contents of this internal buffer may be copied into a string variable using ob_get_contents(). To output what is stored in the internal buffer, use ob_end_flush(). Alternatively, ob_end_clean() will silently discard the buffer contents.

An optional output_callback function may be specified. This function takes a string as a parameter and should return a string. The function will be called when ob_end_flush() is called, or when the output buffer is flushed to the browser at the end of the request. When output_callback is called, it will receive the contents of the output buffer as its parameter and is expected to return a new output buffer as a result, which will be sent to the browser. If the output_callback is not a callable function, this function will return FALSE. If the callback function has two parameters, the second parameter is filled with a bit-field consisting of PHP_OUTPUT_HANDLER_START, PHP_OUTPUT_HANDLER_CONT and PHP_OUTPUT_HANDLER_END.

Note: In PHP 4.0.4, ob_gzhandler() was introduced to facilitate sending gz-encoded data to web browsers that support compressed web pages. ob_gzhandler() determines what type of content encoding the browser will accept and will return its output accordingly.

Note: Before PHP 4.3.2 this function did not return FALSE in case the passed output_callback can not be executed.

Warning

Some web servers (e.g. Apache) change the working directory of a script when calling the callback function. You can change it back by e.g. chdir(dirname($_SERVER['SCRIPT_FILENAME'])) in the callback function.

If the optional parameter chunk_size is passed, the callback function is called on every first newline after chunk_size bytes of output. The output_callback parameter may be bypassed by passing a NULL value.

If the optional parameter erase is set to FALSE, the buffer will not be deleted until the script finishes (as of PHP 4.3.0).

Output buffers are stackable, that is, you may call ob_start() while another ob_start() is active. Just make sure that you call ob_end_flush() the appropriate number of times. If multiple output callback functions are active, output is being filtered sequentially through each of them in nesting order.

ob_end_clean(), ob_end_flush(), ob_clean(), ob_flush() and ob_start() may not be called from a callback function. If you call them from callback function, the behavior is undefined. If you would like to delete the contents of a buffer, return "" (a null string) from callback function. You can't even call functions using the output buffering functions like print_r($expression, true) or highlight_file($filename, true) from a callback function.

Example 1. User defined callback function example

<?php

function callback($buffer)
{
 
// replace all the apples with oranges
 
return (str_replace("apples", "oranges", $buffer));
}

ob_start("callback");

?>
<html>
<body>
<p>It's like comparing apples to oranges.</p>
</body>
</html>
<?php

ob_end_flush
();

?>

Would produce:

<html>
<body>
<p>It's like comparing oranges to oranges.</p>
</body>
</html>

See also ob_get_contents(), ob_end_flush(), ob_end_clean(), ob_implicit_flush(), ob_gzhandler(), ob_iconv_handler() mb_output_handler(), and ob_tidyhandler().



User Contributed Notes
ob_start
rafa dot chacon at factorydea dot com
10-May-2005 04:10
If you're trying to include a php file inside a loop by require_once (in example, a dinamic email template) and change the value of some variables (in example, url to unsuscribe, different for each user), you should use

<?php

// ... some code

$usermail = array("email1", "email2", ...);

for(
$i = 0; $i < $MAX; $i++)
{
      
$usermail_unsuscribe = $usermail[$i];
      
ob_start();
       include(
"email_template.php");
      
ob_clean();
}
?>

Otherwise $usermail_unsuscribe will get only "email1" value.
JM
08-May-2005 02:17
I don't claim to understand this--I would have expected the exact opposite--but it seems that
  ob_start() ... ob_end_flush()
can massively improve perfomance, by at least a factor of 10 (admittedly a small number of samples).

I tried this after discovering that I could move a large (100ms) bottleneck in one of my scripts into
   echo "<!-- about 40 characters of junk -->";
which clearly shouldn't have taken long to run.

My unfounded theory is that without buffering, the interaction between PHP4.3.4 and Apache is not optimized, whereas with buffering, PHP delivers the entire page at once, which Apache handles better.

I should add that this is under https.
Ray Paseur (Paseur ... ImagineDB.com)
01-Mar-2005 03:50
You can use PHP to generate a static HTML page.  Useful if you have a complex script that, for performance reasons, you do not want site visitors to run repeatedly on demand.  A "cron" job can execute the PHP script to create the HTML page.  For example:

<?php // CREATE index.html
  
ob_start();
/* PERFORM COMLEX QUERY, ECHO RESULTS, ETC. */
  
$page = ob_get_contents();
  
ob_end_clean();
  
$cwd = getcwd();
  
$file = "$cwd" .'/'. "index.html";
   @
chmod($file,0755);
  
$fw = fopen($file, "w");
  
fputs($fw,$page, strlen($page));
  
fclose($fw);
   die();
?>
eddie
13-Feb-2005 10:09
I use this function for deleting not needed characters within the html code before sending the whole stuff to the browser.

function callback($buffer){
   $buffer = str_replace("\n", "", $buffer);
   $buffer = str_replace("\t", "", $buffer);
   $buffer = str_replace(chr(13), "", $buffer);
   $buffer = ereg_replace("<!\-\- [\/\ a-zA-Z]* \-\->", "", $buffer);
   return $buffer;
}

First str_replace will delete any newlines, second any tabs and the third any carriage return. Finally the regular expression will delete any html-comment which consists of /, space, a-z or A-Z.
Using this saves about 1kb on every pageload.
FB
02-Feb-2005 08:59
I've noticed a bug with MSIE for non cached contents if your page is less than 4096 octets : you have to refresh the page each time to view its content !

Here is the solution to prevent this stupid behaviour of MSIE : just insert this code at the top of your scripts :

function ob_callback($buffer)
{
   return $buffer . str_repeat(' ', max(0, 4097 - strlen($buffer)));
}

ob_start('ob_callback');
master at acmetranslation dot com
31-Dec-2004 04:03
我用这函数实现了动态的url输出rewrite:
<a href="www.paper-translation.com/classical.php">这里</a>
d_spagnoli at yahoo dot it
28-Dec-2004 08:39
nl2br() is not a callable function, to make it work define a new one like this:

function mynl2br($str){
   return nl2br($str);
}

example:

ob_start("nl2br");
echo "under pressure\npushing down on me";
$str_error=ob_get_flush();

doesn't work, use ob_start("mynl2br") instead.

PHP 4.3.9
aaron at offtone.com
13-Nov-2004 07:19
My callback is stored in a function class, and using ob_start ('Class::callback') wasn't working. Not wanting to instantiate the class (no need, it's a function class) I tried this and it worked a charm:

ob_start (array (Class, 'callback'));

PHP 4.3.4
dev at kiwicore dot org
28-Oct-2004 03:49
I wanted to do things a very particular way with output buffering and shutdown functions; using register_shutdown_function instead of the built in callback feature of this function. However, one should note that this won't work, because the contents of the buffer are no longer in scope when PHP is calling the shutdown functions. This would have been easy to see EXCEPT that PHP graciously flushes any unsent buffers at the end of the script, or when calling exit. So:

<?php
   ob_start
();
   echo
'hi';
   exit;
?>

Prints "hi". In a nutshell, if you want it to have a shutdown function that handles an output buffer, just specify it in ob_start() and let PHP automatically call it at the end of the script.
jkloss at hotmail dot com
17-Mar-2004 09:20
If ob_start does not seem to be working for you, note that with Apache 2 the flush() function causes PHP to send headers regardless of whether ob_start had been called before flush.

ob_start();
echo 'test';
flush();

will cause Apache 2 to send whatever headers may be stacked up - which means you can't use a header(location:xxx) after the flush.  To fix, remove the flush().  Spent several hours discovering this.  Apache 1.x didn't work this way.
mjr
10-Mar-2004 11:10
If you're using object-orientated code in PHP you may, like me, want to use a call-back function that is inside an object (i.e. a class function). In this case you send ob_start a two-element array as its single argument. The first element is the name of the object (without the $ at the start), and the second is the function to call. So to use a function 'indent' in an object called '$template' you would use <?php ob_start(array('template', 'indent')); ?>.
zeisss at web dot de
23-Nov-2003 11:03
Note that the current working directory changes in the callback procedure (Changed from htdocs\ to windows\system32\ on my system).

You have to use absolut paths if you want to open files on your local system.
ed.oohay (a) suamhcs_rodnan
21-Nov-2003 07:18
Output Buffering even works in nested scopes or might be applied in recursive structures... thought this might save someone a little time guessing and testing :)

<pre><?php
  
   ob_start
();              // start output buffer 1
  
echo "a";                // fill ob1
      
      
ob_start();              // start output buffer 2
      
echo "b";                // fill ob2
      
$s1 = ob_get_contents(); // read ob2 ("b")
      
ob_end_flush();          // flush ob2 to ob1
      
  
echo "c";                // continue filling ob1
  
$s2 = ob_get_contents(); // read ob1 ("a" . "b" . "c")
  
ob_end_flush();          // flush ob1 to browser
  
   // echoes "b" followed by "abc", as supposed to:
  
echo "<HR>$s1<HR>$s2<HR>";
  
?></pre>

... at least works on Apache 1.3.28

Nandor =)
venky_athome at yahoo dot com
17-Jan-2003 11:58
IE 55. sp2 and IE6 as on the date of adding this note have problems with content type gzip and caching http headers. The pages are never cached. I think this combination of http headers can also crash the browser.

see http://support.microsoft.com/default.aspx?scid=kb;en-us;321722
05-Dec-2002 02:02
If you're using Apache (1.3x or 2.0), you might consider adding automatic compression capability to your delivered pages.

I assume you all know how to build compression classes and use them in your programs, but none has yet to offer the speed and robustness of a binary-compiled module. Furthermore, such modules also log the "compressable" hit in the web log file, thus allowing your favorite web anaysing program to show you reports of bandwidth saved.

Having said that, you might consider the following two modules for Apache:

1) Apache 1.3x: use mod_gzip, available from:
http://sourceforge.net/projects/mod-gzip/

2) Apache 2.x: use mod_gz, see here:
http://www.mail-archive.com/dev@httpd.apache.org/msg00734.html

3) Apache 1.3x: you may also want to use mod_defalte, from:
ftp://ftp.lexa.ru/pub/apache-rus/contrib/

Hope it helps.
cliff at NOSPAMtravelguides dot com
07-Aug-2002 05:36
good article on output buffering on devshed:

http://www.devshed.com/c/a/PHP/Output-Buffering-With-PHP

<ob_list_handlersoutput_add_rewrite_var>
 Last updated: Thu, 19 May 2005
Copyright © 2001-2005 The PHP Group
All rights reserved.
This unofficial mirror is operated at: The Server Pages
Last updated: Thu May 19 17:35:34 2005 CDT