Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
Sends error to Slack via Webhook
// Set your Slack WEBHOOK here
// Register function that will be executed in the end of PHP runtime
* Sends a message to channel on Slack, example:
Error (E_ERROR) | PHP Stopped
Message (Uncaught Exception: Error Handler(\Error) not foundError Object
...error details...
* In order to make it work, just define a constant somewhere like:
* ...where <WEBHOOK> is the webhook you received from Slack
* */
function shutdown_error_handler()
$slackWebhookUrlIsDefined = defined('_SLACK_ERRORS_CHANNEL_WEBHOOK_URL');
if (!$slackWebhookUrlIsDefined) return;
$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, [
//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://
$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
$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);
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
You can’t perform that action at this time.