简体   繁体   中英

PHP exit and still output buffer

Is it possible to exit the script, say on a fatal error and still output my buffer? I am using a template system that executes the header/content/footer. So I am trying to make it so it'll stop code executing on the fatal_error() function but still output the buffer template (which sends out the error message to the user while still maintaining the website template.) I use ob_start("ob_gzhandler") and in my fatal_error() function I use ob_flush() and I end up with a white screen when fatal_error() is called. Here's my function

function fatal_error($error_message, $log = true)
{
    setup_error($error_message);

    ob_flush();
    exit();
}

setup_error() tells the script to change the content body to the error message (so it doesn't parse 1/2 the body when the error occurs). All the examples I've looked through says ob_flush() or ob_end_flush() can achieve this, though I'm not having any luck.

Use the set_error_handler() function. This way you can assign a user-defined function, in your case fatal_error() , to execute when PHP encounters an error. You can do whatever you like in your function, including flushing the buffer and exiting.

EDIT:

The following code should do what you want:

set_error_handler('fatal_error', E_ERROR, E_USER_ERROR);

function fatal_error($errno, $errstr, $errfile, $errline)
{
    ob_flush();
    exit();
}

EDIT 2:

You can trigger an E_ERROR and therefore test the fatal_error() function like so:

trigger_error('This is a test error', E_ERROR);

I would try also adding a call to flush() before the ob_flush() . Sometimes, both are needed.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM