Today we’re going to learn how to create a handler to redirect PHP errors to the Linux or Docker console.
The first thing we need to do is to create a handler, we can call it exception_handler.php.
And let’s add the following:
<?php function handleException($exception) { // Get information about the exception $message = 'ERR: An error occurred on the website.' . "\n\n"; $message .= 'ERR: Error message: ' . $exception->getMessage() . "\n"; $message .= 'ERR: File: ' . $exception->getFile() . "\n"; $message .= 'ERR: Line: ' . $exception->getLine() . "\n"; $message .= 'ERR: HTTP status code: ' . http_response_code() . "\n"; $currentDate = date('Y-m-d H:i:s'); $errorString = $currentDate . " IP: [" . $_SERVER['REMOTE_ADDR'] . "] " . $message; } // Set the custom exception handling function set_exception_handler('handleException');
This function will give us all the necessary information to identify the error, the error message, the file, the line, and the error code. In addition to the date and the IP from where the call was made.
NOTE: you must put $_SERVER[‘HTTP_X_REAL_IP’] if you use a reverse proxy, instead of $_SERVER[‘REMOTE_ADDR’];
Now we just have to include this file in the files that we want to audit errors by doing an include:
include_once('../extras/exception_handler.php');