Sends error to Slack via Webhook
<?php | |
// Set your Slack WEBHOOK here | |
define('_SLACK_ERRORS_CHANNEL_WEBHOOK_URL', '<WEBHOOK>'); | |
// Register function that will be executed in the end of PHP runtime | |
register_shutdown_function("shutdown_error_handler"); | |
/* | |
* Sends a message to channel on Slack, example: | |
* | |
* | |
Error (E_ERROR) | PHP Stopped | |
File (/PATH/TO/FILE:LINE) | |
Message (Uncaught Exception: Error Handler(\Error) not foundError Object | |
( | |
...error details... | |
) | |
* | |
* In order to make it work, just define a constant somewhere like: | |
* define('_SLACK_ERRORS_CHANNEL_WEBHOOK_URL', '<WEBHOOK>'); | |
* | |
* ...where <WEBHOOK> is the webhook you received from Slack | |
* | |
* */ | |
function shutdown_error_handler() | |
{ | |
$slackWebhookUrlIsDefined = defined('_SLACK_ERRORS_CHANNEL_WEBHOOK_URL'); | |
if (!$slackWebhookUrlIsDefined) return; | |
$slackWebhookUrl = _SLACK_ERRORS_CHANNEL_WEBHOOK_URL; | |
$lasterror = error_get_last(); | |
$type = $lasterror['type']; | |
$typeName = FriendlyErrorType($type); | |
$message = $lasterror['message']; | |
$file = $lasterror['file']; | |
$line = $lasterror['line']; | |
// Choose which errors you want to be sent to Slack | |
// If your code generates too many Warnings, you can | |
// comment them out from the array | |
if(isset($lasterror) && in_array($typeName, [ | |
'E_WARNING', 'E_CORE_WARNING', 'E_USER_WARNING', | |
'E_ERROR', 'E_COMPILE_ERROR', 'E_USER_ERROR', | |
'E_PARSE', | |
])) | |
{ | |
//Figure out whether we are using http or https. | |
$http = 'http'; | |
//If HTTPS is present in our $_SERVER array, the URL should | |
//start with https:// instead of http:// | |
if(isset($_SERVER['HTTPS'])){ | |
$http = 'https'; | |
} | |
//Get the HTTP_HOST. | |
$host = $_SERVER['HTTP_HOST']; | |
//Get the REQUEST_URI. i.e. The Uniform Resource Identifier. | |
$requestUri = $_SERVER['REQUEST_URI']; | |
//Finally, construct the full URL. | |
//Use the function htmlentities to prevent XSS attacks. | |
$full_url = $http . '://' . htmlentities($host) . htmlentities($requestUri); | |
$payload = [ | |
'text' => " | |
*{$typeName}* occured in \n | |
`{$file}` on line `{$line}` \n | |
On URL: {$full_url} \n | |
Here is what I know about it: \n | |
```{$message}```", | |
]; | |
$ch = curl_init($slackWebhookUrl); | |
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST'); | |
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload)); | |
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true); | |
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); | |
curl_setopt($ch, CURLOPT_HTTPHEADER, array( | |
'Content-Type: application/json', | |
)); | |
$result = curl_exec($ch); | |
curl_close($ch); | |
if($result === false) | |
{ | |
die('Curl error: ' . curl_error($ch)); | |
} | |
} | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment