Header menu

_________________________________________________________________________________

Tuesday, 4 February 2014

Stop/Hold output before sending of header


ob_start()

Normally, the output  starts as soon as your first "echo" comes  or first non-PHP content. Once output starts, we cannot send headers . So to tackle this we use output buffering we is disabled by default.  

To create a new output buffer and start writing it, we call ob_start(). There are two ways to end a buffer :-

1.  ob_end_flush()
      It ends the buffer and sends all data to output

2.  ob_end_clean()
      It ends the buffer without sending it to output.

Consider the following script:

<?php
    ob_start();
    echo
"Hello One!\n";
    
ob_end_flush();

    
ob_start();
    echo
"Hello Two!\n";
    
ob_end_clean();

    
ob_start();
    echo
"Hello Three!\n";
?>

Output :  Hello One! Hello Three!

This script will output "Hello One" because the first text is placed into a buffer then flushed with ob_end_flush().

The "Hello Two" will not be printed out, although it is echoed, because it is placed into a buffer which is cleaned using ob_end_clean() and not sent to output.

Finally, the script will print out "Hello Three" because PHP automatically flushes  output buffers when it reaches at the end of a script.

No comments:

Post a Comment