#1
  1. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2003
    Posts
    349
    Rep Power
    12

    Should I use ob_start() ob_end_flush()?


    Hello.

    I downloaded a script that looks something like this:
    PHP Code:
    <?php
    ob_start
    ();

    include(
    "openDatabaseConnnection.php");

    ob_end_flush();

    include (
    "header.php");
    include (
    "content.php");
    include (
    "footer.php");

    include(
    "lib/closeCon.php");
    ?>
    If I take out ob_start() and ob_end_flush() it still works.

    What is this doing and is it necesary? I searched google and php.net but got confused by techno jargon. What does it actually do and should I use it?

    Thanks ;-)
  2. #2
  3. Contributing User
    Devshed Novice (500 - 999 posts)

    Join Date
    Mar 2004
    Location
    Central Washington (USA)
    Posts
    518
    Rep Power
    11
    ob_start and ob_end_flush are output buffering functions. basically, from when you call ob_start(), you store the script output into a buffer rather than just writing the output file. When you call ob_end_flush, the output is finalized and sent to the browser. I have found these useful for a couple of reasons. First, if you wish to redirect or set header contents from different parts of your script, you can call ob_start before any output ob_end_flush when you're done making changes to the header. This way you avoid the error message 'Warning: Cannot modify header information - headers already sent by (output started at ...) in ... on line ...'.

    Here is a script that causes this error:
    PHP Code:
    echo 'hello world';
    header('location: index.php'); 
    The error could be avoided by using:
    PHP Code:
    ob_start();
    echo 
    'hello world';
    header('location: index.php');
    ob_end_flush(); 
    Another use would be if you have a big page and you'd like to send, say, the banner first and then the page contents. You can call ob_end_flush after the banner portion of your script and then call ob_end_flush after the rest is finished. This way the user will see the banner load rather quickly and then the rest of the page will load (like devshed!).

    Hope this helps.
  4. #3
  5. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2003
    Posts
    349
    Rep Power
    12
    Thank you for your clear explanation.

    I have been anoyed for months by headers already sent by ... errors caused by white space before or after the <? and ?> tags in files I call using include() before the headers of some of my scripts. (the whitespace is added as a "free bonus" by my web based script editor)

    Not only will I leave the buffering functions in the script I downloaded, I will add it to some of my other scripts as well.

    Cheers.

IMN logo majestic logo threadwatch logo seochat tools logo