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?
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);
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.
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.
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.
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.
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()).
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With