Thursday, November 11, 2010

Wednesday, November 10, 2010

PHP Object Buffering ob_start() and ob_flush()

PHP Object Buffering

bool ob_start ( [callback output_function])
bool ob_end_flush ( void )
bool ob_end_clean ( void )

There are two ways to start buffering output:
through a setting in php.ini to enable output
buffering for all scripts, or by using a function
call on a script-by-script basis. Surprisingly,
the latter is preferred - it makes your code
more portable, and also gives you greater flexibility.

To create a new output buffer and start
writing to it, call ob_start(). There are
two ways to end a buffer, which are ob_end_flush()
and ob_end_clean() - the former ends the buffer
and sends all data to output, and the latter ends
the buffer without sending it to output.
Every piece of text outputted while an output
buffer is open is placed into that buffer
as opposed to being sent to output.
Consider the following script:

ob_start();
print "Hello First!\n";
ob_end_flush();

ob_start();
print "Hello Second!\n";
ob_end_clean();

ob_start();
print "Hello Third!\n";
?>

ob_start();
print "Hello First!\n";
ob_end_flush();

ob_start();
print "Hello Second!\n";
ob_end_clean();

ob_start();
print "Hello Third!\n";
?>



Reusing buffers



void ob_flush ( void )
void ob_clean ( void )

The functions ob_end_flush() and ob_end_clean()
are complemented by ob_flush() and ob_clean() -
these do the same jobs as their longer cousins,
with the difference that they do not end the output buffer.
We could rewrite the previous script like this:

ob_start();
print "Hello First!\n";
ob_flush();
print "Hello Second!\n";
ob_clean();
print "Hello Third!\n";
?>

This time the buffer is flushed but left open,
then cleaned and still left open, and finally
automatically closed and flushed by PHP as the
script ends - this saves creating and destroying
output buffers. Reusing buffers like this is
about 60% faster than opening and closing buffers
all the time, and is a smart move if you ever find
yourself in this situation.



Refer this page for more PHP buffering.

Wednesday, November 3, 2010