ob_start
(PHP 4, PHP 5)
ob_start — Turn on output buffering
Description
$output_callback
= NULL
[, int $chunk_size
= 0
[, int $flags
= PHP_OUTPUT_HANDLER_STDFLAGS
]]] )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.
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.
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.
Parameters
-
output_callback
-
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 the output buffer is flushed (sent) or cleaned (with ob_flush(), ob_clean() or similar function) or when the output buffer is flushed to the browser at the end of the request. Whenoutput_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 theoutput_callback
is not a callable function, this function will returnFALSE
. This is the callback signature:string handler ( string$buffer
[, int$phase
] )-
buffer
- Contents of the output buffer.
-
phase
-
Bitmask of
PHP_OUTPUT_HANDLER_*
constants.
If
output_callback
returnsFALSE
original input is sent to the browser.The
output_callback
parameter may be bypassed by passing aNULL
value.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.
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.
-
-
chunk_size
-
If the optional parameter
chunk_size
is passed, the buffer will be flushed after any output call which causes the buffer's length to equal or exceedchunk_size
. The default value 0 means that the output function will only be called when the output buffer is closed.Prior to PHP 5.4.0, the value 1 was a special case value that set the chunk size to 4096 bytes.
-
flags
-
The
flags
parameter is a bitmask that controls the operations that can be performed on the output buffer. The default is to allow output buffers to be cleaned, flushed and removed, which can be set explicitly viaPHP_OUTPUT_HANDLER_CLEANABLE
|PHP_OUTPUT_HANDLER_FLUSHABLE
|PHP_OUTPUT_HANDLER_REMOVABLE
, orPHP_OUTPUT_HANDLER_STDFLAGS
as shorthand.Each flag controls access to a set of functions, as described below:
Constant Functions PHP_OUTPUT_HANDLER_CLEANABLE
ob_clean(), ob_end_clean(), and ob_get_clean(). PHP_OUTPUT_HANDLER_FLUSHABLE
ob_end_flush(), ob_flush(), and ob_get_flush(). PHP_OUTPUT_HANDLER_REMOVABLE
ob_end_clean(), ob_end_flush(), and ob_get_flush().
Return Values
Returns TRUE
on success or FALSE
on failure.
Changelog
Version | Description |
---|---|
5.4.0 |
The third parameter of ob_start() changed from a
boolean parameter called erase
(which, if set to FALSE , would prevent the output buffer from being
deleted until the script finished executing) to an
integer parameter called flags .
Unfortunately, this results in an API compatibility break for code
written prior to PHP 5.4.0 that uses the third parameter. See
the flags example
for an example of how to handle this with code that needs to be
compatible with both.
|
5.4.0 | A chunk size of 1 now results in chunks of 1 byte being sent to the output buffer. |
4.3.2 |
This function was changed to return FALSE in case the passed
output_callback can not be executed.
|
4.2.0 |
Added the erase parameter.
|
Examples
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();
?>
The above example will output:
<html> <body> <p>It's like comparing oranges to oranges.</p> </body> </html>
Example #2 Creating an uneraseable output buffer in a way compatible with both PHP 5.3 and 5.4
<?php
if (version_compare(PHP_VERSION, '5.4.0', '>=')) {
ob_start(null, 0, PHP_OUTPUT_HANDLER_STDFLAGS ^
PHP_OUTPUT_HANDLER_REMOVABLE);
} else {
ob_start(null, 0, false);
}
?>
See Also
- ob_get_contents() - Return the contents of 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_implicit_flush() - Turn implicit flush on/off
- ob_gzhandler() - ob_start callback function to gzip output buffer
- ob_iconv_handler() - Convert character encoding as output buffer handler
- mb_output_handler() - Callback function converts character encoding in output buffer
- ob_tidyhandler() - ob_start callback function to repair the buffer
Коментарии
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 =)
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();
?>
When you rely on URL rewriting to pass the PHP session ID you should be careful with ob_get_contents(), as this might disable URL rewriting completely.
Example:
ob_start();
session_start();
echo '<a href=".">self link</a>';
$data = ob_get_contents();
ob_end_clean();
echo $data;
In the example above, URL rewriting will never occur. In fact, rewriting would occur if you ended the buffering envelope using ob_end_flush(). It seems to me that rewriting occurs in the very same buffering envelope where the session gets started, not at the final output stage.
If you need a scenario like the one above, using an "inner envelope" will help:
ob_start();
ob_start(); // add the inner buffering envelope
session_start();
echo '<a href=".">self link</a>';
ob_end_flush(); // closing the inner envelope will activate URL rewriting
$data = ob_get_contents();
ob_end_clean();
echo $data;
In case you're interested or believe like me that this is rather a design flaw instead of a feature, please visit bug #35933 (http://bugs.php.net/bug.php?id=35933) and comment on it.
Hello firends
ob_start() opens a buffer in which all output is stored. So every time you do an echo, the output of that is added to the buffer. When the script finishes running, or you call ob_flush(), that stored output is sent to the browser (and gzipped first if you use ob_gzhandler, which means it downloads faster).
The most common reason to use ob_start is as a way to collect data that would otherwise be sent to the browser.
These are two usages of ob_start():
1-Well, you have more control over the output. Trivial example: say you want to show the user an error message, but the script has already sent some HTML to the browser. It'll look ugly, with a half-rendered page and then an error message. Using the output buffering functions, you can simply delete the buffer and sebuffer and send only the error message, which means it looks all nice and neat buffer and send
2-The reason output buffering was invented was to create a seamless transfer, from: php engine -> apache -> operating system -> web user
If you make sure each of those use the same buffer size, the system will use less writes, use less system resources and be able to handle more traffic.
With Regards, Hossein
When a script ends, all buffered output is flushed (this is not a bug: http://bugs.php.net/bug.php?id=42334&thanks=4). What happens when the script throws an error (and thus ends) in the middle of an output buffer? The script spits out everything in the buffer before printing the error!
Here is the simplest solution I have been able to find. Put it at the beginning of the error handling function to clear all buffered data and print only the error:
$handlers = ob_list_handlers();
while ( ! empty($handlers) ) {
ob_end_clean();
$handlers = ob_list_handlers();
}
Careful with while using functions that change headers of a page; that change will not be undone when ending output buffering.
If you for instance have a class that generates an image and sets the appropriate headers, they will still be in place after the end of ob.
For instance:
<?php
ob_start();
myClass::renderPng(); //header("Content-Type: image/png"); in here
$pngString = ob_get_contents();
ob_end_clean();
?>
will put the image bytes into $pngString, and set the content type to image/png. Though the image will not be sent to the client, the png header is still in place; if you do html output here, the browser will most likely display "image error, cannot be viewed", at least firefox does.
You need to set the correct image type (text/html) manually in this case.