Delicious Bookmark this on Delicious Share on Facebook SlashdotSlashdot It! Digg! Digg



PHP : Function Reference : Output Control Functions

Output Control Functions

Introduction

The Output Control functions allow you to control when output is sent from the script. This can be useful in several different situations, especially if you need to send headers to the browser after your script has began outputting data. The Output Control functions do not affect headers sent using header() or setcookie(), only functions such as echo() and data between blocks of PHP code.

Note:

When upgrading from PHP 4.1.x (and 4.2.x) to 4.3.x due to a bug in earlier versions you must ensure that implict_flush is OFF in your php.ini, otherwise any output with ob_start() will not be hidden from output.

Requirements

No external libraries are needed to build this extension.

Installation

There is no installation needed to use these functions; they are part of the PHP core.

Runtime Configuration

The behaviour of these functions is affected by settings in php.ini.

Table 236. Output Control configuration options

Name Default Changeable Changelog
output_buffering "0" PHP_INI_PERDIR  
output_handler NULL PHP_INI_PERDIR Available since PHP 4.0.4.
implicit_flush "0" PHP_INI_ALL PHP_INI_PERDIR in PHP <= 4.2.3.


For further details and definitions of the PHP_INI_* constants, see the Appendix I, php.ini directives.

Here's a short explanation of the configuration directives.

output_buffering boolean/integer

You can enable output buffering for all files by setting this directive to 'On'. If you wish to limit the size of the buffer to a certain size - you can use a maximum number of bytes instead of 'On', as a value for this directive (e.g., output_buffering=4096). As of PHP 4.3.5, this directive is always Off in PHP-CLI.

output_handler string

You can redirect all of the output of your scripts to a function. For example, if you set output_handler to mb_output_handler(), character encoding will be transparently converted to the specified encoding. Setting any output handler automatically turns on output buffering.

Note:

You cannot use both mb_output_handler() with ob_iconv_handler() and you cannot use both ob_gzhandler() and zlib.output_compression.

Note:

Only built-in functions can be used with this directive. For user defined functions, use ob_start().

implicit_flush boolean

FALSE by default. Changing this to TRUE tells PHP to tell the output layer to flush itself automatically after every output block. This is equivalent to calling the PHP function flush() after each and every call to print() or echo() and each and every HTML block.

When using PHP within an web environment, turning this option on has serious performance implications and is generally recommended for debugging purposes only. This value defaults to TRUE when operating under the CLI SAPI.

See also ob_implicit_flush().

Resource Types

This extension has no resource types defined.

Predefined Constants

This extension has no constants defined.

Examples

Example 1682. Output Control example

<?php

ob_start
();
echo
"Hello\n";

setcookie("cookiename", "cookiedata");

ob_end_flush();

?>


In the above example, the output from echo() would be stored in the output buffer until ob_end_flush() was called. In the mean time, the call to setcookie() successfully stored a cookie without causing an error. (You can not normally send headers to the browser after data has already been sent.)

See Also

See also header() and setcookie().

Table of Contents

flush — Flush 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_flush — Flush the output buffer, return it as a string and turn off output buffering
ob_get_length — Return the length of the output buffer
ob_get_level — Return the nesting level of the output buffering mechanism
ob_get_status — Get status of output buffers
ob_gzhandler — ob_start callback function to gzip output buffer
ob_implicit_flush — Turn implicit flush on/off
ob_list_handlers — List all output handlers in use
ob_start — Turn on output buffering
output_add_rewrite_var — Add URL rewriter values
output_reset_rewrite_vars — Reset URL rewriter values

Code Examples / Notes » ref.outcontrol

erwinx

[Concerns IE refusing to jump to a #something in the URL.]
I encoutered a bug in IE6/W2000 that can be solved by turning output buffering on.
Maybe it also helps in other situations/M$-OS, not sure.
Situation:
A page with a hash in the URL, and IE doesn't jump to that location.
Example:
http://www.bla.com/test.php#something
- In test.php the anchortag is placed normally like:
<a name="something">
</a>
- test.php takes a few seconds to load because of heavy-duty database activity.
IE just ignores the hash #something.
It looks like IE 'forgets' the hash if it hasn't encoutered it YET in the HTML.
Turning output buffering on resolves that issue.


trucex um,

Unfortunately, the PHP guys didn't build support into any of the image output functions to return the image instead of outputting it.
Fortunately, we have output buffering to fix that.
<?
$im = imagecreatetruecolor(200, 200);
// Other image functions here...
ob_start();
imagepng($im);
$imageData = ob_get_contents();
ob_clean();
?>
You can now use the $imageData variable to either create another GD image, save it, put it in a database, make modifications to the binary, or output it to the user. You can easily check the size of it as well without having to access the disk...just use strlen();


tijmen

Trying to benchmark your server when using output_buffering ?
Don't forget that the value 4096 in the php.ini will give you complete different loadtimes compares to the value of 1.
In the first case the output will be sent after buffering 4096 and the loadtime timed at the end of the page will contain the loadtime needed to download the complete page in the clientbrowser while the second value will contain the loadtime needed to place the complete page in the buffer. The time needed for sending is not clocked.
This can be very frustrating if you don't see the differance between server and the 1st is using 4096 instead of 1.
Although technically much faster than the second server the second server was providing much better loadtime results.
This result will grow when using large amounts of output.
But this becomes interesting if you want to measure the time needed for the page to be loaded for the client.


nobbie @t php d0t net

There is a problem in MSIE 5.5,6 with regards to Page compression. Users might experience pages not loading completely, or just a blank page.
This articles you are looking for is what you're looking for:
Microsoft Knowledge Base Article - 312496 (for MSIE 6)
Microsoft Knowledge Base Article - 313712 (for MSIE 5.5)
It states that you should upgrade to the latest MSIE Service Pack to fix the following problem:
Internet Explorer May Lose the First 2,048 Bytes of Data That Are Sent Back from a Web Server That Uses HTTP Compression


basicartsstudios

Sometimes you might not want to include a php-file under the specifications defined in the functions include() or require(), but you might want to have in return the string that the script in the file "echoes".
Include() and require() both directly put out the evaluated code.
For avoiding this, try output-buffering:
<?php
ob_start();
eval(file_get_contents($file));
$result = ob_get_contents();
ob_end_clean();
?>
or
<?php
ob_start();
include($file);
$result = ob_get_contents();
ob_end_clean();
?>
which i consider the same, correct me if I'm wrong.
Best regards, BasicArtsStudios


kamermans

Output buffering is set to '4096' instead of 'Off' or '0' by default in the php-5.0.4-10.5 RPM for Fedora Core release 4 (Stentz).  This has cost me much time!

webmaster

Now this just blew my mind. I had a problem with MySQL being incredibly slow on Windows 2003 running IIS... on ASP/VBScript pages. PHP is also installed on the server and so is Microsoft SQL 2005 Express. (Yes, we're running ASP, PHP, MySQL and MS SQL on the same Windows 2003 Server using IIS.)
I was browsing the internet for a solution and saw a suggestion that I change output_buffering to on if MySQL was slow for PHP pages.  Since we also served PHP pages with MySQL from the same server, it caught my eye.  For the hell of it, I went into php.ini and changed output_buffering to on and suddenly MySQL and ASP was faster... MySQL and PHP was faster... Microsoft SQL Server 2005 Express and ASP was faster.... everything was faster... even stuff that had no PHP!
And I didn't even have to restart IIS. As soon as I saved the php.ini file with the change, everything got faster.
Apparently PHP and MySQL and IIS are so intertwined somehow that changing the buffering setting really effects the performance of the entire server.
So, if you are having performance problems on Windows 2003 & IIS, you might try setting output_buffering = On in php.ini if you happen to have PHP installed.  Having it set to off apparently effects the performance of Windows 2003 and IIS severely... even for webpages that do not use PHP or MySQL.


jgeewax a t gmail

It seems that while using output buffering, an included file which calls die() before the output buffer is closed is flushed rather than cleaned. That is, ob_end_flush() is called by default.
<?php
// a.php (this file should never display anything)
ob_start();
include('b.php');
ob_end_clean();
?>
<?php
// b.php
print "b";
die();
?>
This ends up printing "b" rather than nothing as ob_end_flush() is called instead of ob_end_clean(). That is, die() flushes the buffer rather than cleans it. This took me a while to determine what was causing the flush, so I thought I'd share.


webmaster

In re to erwinX at darwineX dot nl:
Adding an ampersand (&) before the hash seems to work too (for me at least), i.e.: http://somedomain.tld/blah.php?arg=x&#something
I guess php then interperts it as an argument to the script. Might save some time and resources.


kend52

I ran out of memory, while output buffering and drawing text on imported images. Only the top portion of the 5MP image was displayed by the browser.  Try increasing the memory limit in either the php.ini file( memory_limit = 16M; ) or in the .htaccess file( php_value memory_limit "16M" ). Also see function memory_get_usage() .

gruik

For those who are looking for optimization, try using buffered output.
I noticed that an output function call (i.e echo()) is somehow time expensive. When using buffered output, only one output function call is made and it seems to be much faster.
Try this :
<?php
your_benchmark_start_function();
for ($i = 0; $i < 5000; $i++)
echo str_repeat ("your string blablabla bla bla", (rand() % 4) + 1)."
\n";
echo your_benchmark_end_function();
?>
And then :
<?php
your_benchmark_start_function();
ob_start ();
for ($i = 0; $i < 5000; $i++)
echo str_repeat ("your string blablabla bla bla", (rand() % 4) + 1)."
\n";
echo your_benchmark_end_function();
ob_end_flush ();
?>


philip


Change Language


Follow Navioo On Twitter
.NET Functions
Apache-specific Functions
Alternative PHP Cache
Advanced PHP debugger
Array Functions
Aspell functions [deprecated]
BBCode Functions
BCMath Arbitrary Precision Mathematics Functions
PHP bytecode Compiler
Bzip2 Compression Functions
Calendar Functions
CCVS API Functions [deprecated]
Class/Object Functions
Classkit Functions
ClibPDF Functions [deprecated]
COM and .Net (Windows)
Crack Functions
Character Type Functions
CURL
Cybercash Payment Functions
Credit Mutuel CyberMUT functions
Cyrus IMAP administration Functions
Date and Time Functions
DB++ Functions
Database (dbm-style) Abstraction Layer Functions
dBase Functions
DBM Functions [deprecated]
dbx Functions
Direct IO Functions
Directory Functions
DOM Functions
DOM XML Functions
enchant Functions
Error Handling and Logging Functions
Exif Functions
Expect Functions
File Alteration Monitor Functions
Forms Data Format Functions
Fileinfo Functions
filePro Functions
Filesystem Functions
Filter Functions
Firebird/InterBase Functions
Firebird/Interbase Functions (PDO_FIREBIRD)
FriBiDi Functions
FrontBase Functions
FTP Functions
Function Handling Functions
GeoIP Functions
Gettext Functions
GMP Functions
gnupg Functions
Net_Gopher
Haru PDF Functions
hash Functions
HTTP
Hyperwave Functions
Hyperwave API Functions
i18n Functions
IBM Functions (PDO_IBM)
IBM DB2
iconv Functions
ID3 Functions
IIS Administration Functions
Image Functions
Imagick Image Library
IMAP
Informix Functions
Informix Functions (PDO_INFORMIX)
Ingres II Functions
IRC Gateway Functions
PHP / Java Integration
JSON Functions
KADM5
LDAP Functions
libxml Functions
Lotus Notes Functions
LZF Functions
Mail Functions
Mailparse Functions
Mathematical Functions
MaxDB PHP Extension
MCAL Functions
Mcrypt Encryption Functions
MCVE (Monetra) Payment Functions
Memcache Functions
Mhash Functions
Mimetype Functions
Ming functions for Flash
Miscellaneous Functions
mnoGoSearch Functions
Microsoft SQL Server Functions
Microsoft SQL Server and Sybase Functions (PDO_DBLIB)
Mohawk Software Session Handler Functions
mSQL Functions
Multibyte String Functions
muscat Functions
MySQL Functions
MySQL Functions (PDO_MYSQL)
MySQL Improved Extension
Ncurses Terminal Screen Control Functions
Network Functions
Newt Functions
NSAPI-specific Functions
Object Aggregation/Composition Functions
Object property and method call overloading
Oracle Functions
ODBC Functions (Unified)
ODBC and DB2 Functions (PDO_ODBC)
oggvorbis
OpenAL Audio Bindings
OpenSSL Functions
Oracle Functions [deprecated]
Oracle Functions (PDO_OCI)
Output Control Functions
Ovrimos SQL Functions
Paradox File Access
Parsekit Functions
Process Control Functions
Regular Expression Functions (Perl-Compatible)
PDF Functions
PDO Functions
Phar archive stream and classes
PHP Options&Information
POSIX Functions
Regular Expression Functions (POSIX Extended)
PostgreSQL Functions
PostgreSQL Functions (PDO_PGSQL)
Printer Functions
Program Execution Functions
PostScript document creation
Pspell Functions
qtdom Functions
Radius
Rar Functions
GNU Readline
GNU Recode Functions
RPM Header Reading Functions
runkit Functions
SAM - Simple Asynchronous Messaging
Satellite CORBA client extension [deprecated]
SCA Functions
SDO Functions
SDO XML Data Access Service Functions
SDO Relational Data Access Service Functions
Semaphore
SESAM Database Functions
PostgreSQL Session Save Handler
Session Handling Functions
Shared Memory Functions
SimpleXML functions
SNMP Functions
SOAP Functions
Socket Functions
Standard PHP Library (SPL) Functions
SQLite Functions
SQLite Functions (PDO_SQLITE)
Secure Shell2 Functions
Statistics Functions
Stream Functions
String Functions
Subversion Functions
Shockwave Flash Functions
Swish Functions
Sybase Functions
TCP Wrappers Functions
Tidy Functions
Tokenizer Functions
Unicode Functions
URL Functions
Variable Handling Functions
Verisign Payflow Pro Functions
vpopmail Functions
W32api Functions
WDDX Functions
win32ps Functions
win32service Functions
xattr Functions
xdiff Functions
XML Parser Functions
XML-RPC Functions
XMLReader functions
XMLWriter Functions
XSL functions
XSLT Functions
YAZ Functions
YP/NIS Functions
Zip File Functions
Zlib Compression Functions
eXTReMe Tracker