lisovaccaro
lisovaccaro

Reputation: 33946

PHP get warning and error messages?

I want to get warning and error messages into php $variables so I save them to my database.

For example when there is any kind of error, warning or similar:

Parse error: syntax error, unexpected T_VARIABLE in /example.php(136) on line 9
Warning: [...]

I want to get them to variable $error_code

How is this done?

Upvotes: 9

Views: 12592

Answers (4)

lisovaccaro
lisovaccaro

Reputation: 33946

I'm using error_get_last(); until I find a better solution

$lastError = error_get_last();
echo $lastError ? "Error: ".$lastError["message"]." on line ".$lastError["line"] : "";
// Save to db

Upvotes: 2

Ja͢ck
Ja͢ck

Reputation: 173522

For the simple case of just logging them:

set_error_handler(function($errno, $errstr, $errfile, $errline) use ($db) {
    // log in database using $db->query()
});

Instead of just logging them into your database (with the likelihood you will not look at them after a while), you can also let those warnings, notices, etc. generate an Exception:

function exception_error_handler($errno, $errstr, $errfile, $errline)
{
    if (error_reporting()) { // skip errors that were muffled
        throw new ErrorException($errstr, $errno, 0, $errfile, $errline);
    }
}

set_error_handler("exception_error_handler");

Source: ErrorException

An exception will have more serious side effects, so you should have an exception handler in place to prevent the uncaught exception to cause a white page of death.

Upvotes: 12

Javier Brooklyn
Javier Brooklyn

Reputation: 634

There is a variable called $php_errormsg which gets the previous error message. Check here for more info - http://php.net/manual/en/reserved.variables.phperrormsg.php

Upvotes: 0

John Conde
John Conde

Reputation: 219794

Look into set_error_handler()

Sets a user function (error_handler) to handle errors in a script.

This function can be used for defining your own way of handling errors during runtime, for example in applications in which you need to do cleanup of data/files when a critical error happens, or when you need to trigger an error under certain conditions (using trigger_error()).

Upvotes: 3

Related Questions