How can I catch and log PHP fatal errors in CodeIgniter?

if (defined('ENVIRONMENT'))
{
    switch (ENVIRONMENT)
    {
        case 'development':
            error_reporting(E_ALL);
            ini_set('display_errors', '1');
        break;

        case 'testing':
        case 'production':
            error_reporting(0);
        break;

        default:
            exit('The application environment is not set correctly.');
    }
}

When environment is set to production and there's a fatal error, I just get a white screen. If the environment is set to development, the error gets displayed in the browser but it doesn't get logged. I have error logging enabled but it only catches PHP notices and warnings.

I am not sure, But do "try- catch- exception" works in php as it works in java

PHP isn't designed to degrade nicely for fatal errors (i.e. parse errors). I did some research and got the following to work. Hopefully it can help others:

register_shutdown_function('_foo');

function _foo()
{
    if ($error = error_get_last())
    {
        $foo = date('Y-m-d H:i:s') . ' --> ' . $error['file'] . ' --> ' . $error['message'] . ' ' . $error['line'];
        file_put_contents('./logs/fatal_errors.php', "$foo\n", FILE_APPEND);
    }
}

I have error logging enabled but it only catches PHP notices and warnings.

Check your INI file, mine is set to E_ALL and the log shows them.

Thanks Dani for posting your solution :)

I found the same approach but with the use of hooks to register this function on "pre_system" here

Check your INI file, mine is set to E_ALL and the log shows them.

That's the same as line 6 in my initial code snippet. The problem is, it doesn't catch PHP fatal errors that halt script execution.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.