Home » Php » PHP get warning and error messages?

PHP get warning and error messages?

Posted by: admin July 12, 2020 Leave a comment


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?

How to&Answers:

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);


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.


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()).


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


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