Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 320
lisovaccaro Avatar asked Feb 23 '13 03:02

lisovaccaro


People also ask

How do I get warnings in PHP?

Quickly Show All PHP Errors The quickest way to display all php errors and warnings is to add these lines to your PHP code file: ini_set('display_errors', 1); ini_set('display_startup_errors', 1); error_reporting(E_ALL);

How do I find PHP errors?

Look for the entry Configuration File (php. Find the Error handling and logging section of the php. ini file. Make sure that both display_errors = On, display_startup_errors = On and log_errors = On are present and uncommented. Check the value of error_log - this tells you the location of the file errors are logged to.

What is the use of Trigger_error ()?

The trigger_error() function creates a user-level error message. The trigger_error() function can be used with the built-in error handler, or with a user-defined function set by the set_error_handler() function.

How does PHP handle notice error?

Error Logging By default, PHP sends an error log to the server's logging system or a file, depending on how the error_log configuration is set in the php. ini file. By using the error_log() function you can send error logs to a specified file or a remote destination.


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

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.

like image 91
Ja͢ck Avatar answered Oct 01 '22 17:10

Ja͢ck


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

like image 40
John Conde Avatar answered Oct 01 '22 18:10

John Conde