when ,where,how to use ob_start and ob_end_clean

Hello everyone!I come from China!

Thank you for your help!

    In PHP, using constructs such as [man]echo[/man] and [man]print[/man], data is immediately sent across the connection to the browser.

    Some functions (i.e. [man]header/man, [man]setcookie/man, [man]session_start/man, etc.) require that no output be sent before calling them. Why? Because once you output data, HTTP headers are already sent to the browser and these special functions can't add the necessary fields to the headers.

    Using [man]ob_start/man, you can stop PHP from automatically sending data. It will instead load outputted data into memory - a buffer. That way, scripts like this will work just fine:

    <?PHP
    
    ob_start();
    
    echo "This is some outputted text. Normally, this script would fail, but since I'm using output buffering it will work just fine.";
    
    setcookie('aCookie', 'aValue');
    
    ob_end_flush();
    ?>

    Note that you use [man]ob_end_flush/man when you want to send all of the buffered data. [man]ob_end_clean[/b] simply discards the buffered data, never sending it to the browser.

      Also note that probably 99% of the time you could just make a few small changes in your code logic/flow, and then you don't need to use the ob_*() functions (plus you'll probably save a millisecond or two of processing time as well as using less memory).

        Thank you bradgrafelman and NogDog !
        I must work hard to catch up with you!

          Write a Reply...