Search code examples
phpexitoutput-bufferingcoding-style

Output Buffer and die() / exit() function?


I hope everyone's holidays are going well.

Another PHP related question here. I am using output buffers in my script, for what I have recently learned is an invalid reason (so I can pass headers later in the script). I now realize that I should be storing all output in a variable or some other sort of storage until I am ready to output at the end of the script instead of using output buffers. Unfortunately, I have already coding these functions and the spontaneous output of html into my pages already. I was hoping to be able to fix this problem in version 2 of the script, as I have strict deadlines to meet with this version.

To the question at hand. I was planning to do this, but apparently die() and exit() functions do not work so well with output buffers? I have exit() after all of my error messages, and instead of ending the execution at that point, it seems the script keeps going due to the output buffer. I have tested this hypothesis by removing the output buffers and the exit() functions work as expected.

Is there a way I change this behaviour, or should I go back to the drawing board and begin replacing my older pages? Also, can someone please explain to me why we should keep output till the end? I'm always interested in learning.

Thanks in advance everyone! Enjoy the last few days of 2010!


Solution

  • While I'll leave the headier and more abstract questions to more intelligent minds than I, I would recommend that you create a wrapper exit() function to simplify the code when you have errors. i.e-

    if(!$good)
    {
        trigger_error('bleh', E_USER_WARNING);
        errorExit();
    }
    
    function errorExit()
    {
        ob_flush();
        exit();
    }
    

    And replace all your exits with that function call and that way the buffer is flushed and the program will exit at the proper time.