How do I stop PHP output buffering from eating error messages?

喜欢而已 提交于 2019-12-01 04:48:22

问题


Well, now that I've gotten a bit further into it, I realize that this is a stupid question, and wrong. Turns out that the author of the legacy code I maintain was hi-jacking the error log to a different file with a php_init statement. The hi-jacking occurred at the same time as the output buffering was turned on, making it appear as though output buffering was throwing away my error messages.

So, Mr. Moderator, feel free to delete this. Thanks to those who answered in good faith.


Given the following PHP script:

<?php 
error_log('test'); 

ob_start();

error_log('test2');

ob_end_flush();
?>

I get the following error log output:

[04-Feb-2010 11:30:38] test

Why is output buffering eating my error messages? How can I make it stop?

Alternately, is there another way to smuggle messages out of an output buffer, or is it simply a black hole?

(Using PHP 5.2.4-2ubuntu5.10)


回答1:


Exceptions penetrate ob_start() shield

If you want to stop PHP script execution, rather throw an Exception, which will penetrate the ob_start(), ob_end_flush() shield

echo 'before output buffer';
ob_start();
throw new Exception('this will be seen');
ob_end_flush();

Consider creating a Logger class

Don't output directly with your method, rather use a class or a holder which incorporates the log (or error method in your case), eg:

class Logger
{
    private $_messages = array();

    public function __construct()
    {
        $this->_messages['errors'] = array();
        $this->_messages['debug'] = array();
    }

    public function error($msg)
    {
        $this->_messages['errors'][] = $msg;
    }

    public function debug($msg)
    {
        $this->_messages['debug'] = $msg;
    }

    public function getErrors()
    {
        return $this->_messages['errors'];
    }

}

$logger = new Logger();

$logger->error('error1');

ob_start();

$logger->error('error2');

ob_end_flush();

print_r($logger->getErrors());

this way you can rely on the holder object, it will not discard messages and get all errors, that you wanted to display




回答2:


I've never done this in practice, but this should work:

You would have to build a wrapper around error_log() that

  1. stores the output you are buffering using ob_get_contents()
  2. erases the output buffer using ob_clean()
  3. writes out the error message and ob_flush()es it
  4. writes back the stored output using echo()


来源:https://stackoverflow.com/questions/2201841/how-do-i-stop-php-output-buffering-from-eating-error-messages

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!