Last active
September 18, 2023 17:32
-
-
Save xcsrz/29958f2ab7bae24b21b106c933dc8d22 to your computer and use it in GitHub Desktop.
The most simple method to post a message to slack via an 'incoming webhook' from PHP
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function post_slack_message($msg) { | |
$opts = [ | |
'http' => [ | |
'method' => 'POST', | |
'header' => "Content-type: application/json\r\n", | |
'content' => json_encode([ | |
'attachments' => [ | |
[ | |
'color' => '#ff0000', | |
'blocks' => [ | |
[ | |
'type' => 'header', | |
'text' => [ | |
'type' => 'plain_text', | |
'text' => $msg, | |
] | |
] | |
] | |
], | |
] | |
]), | |
'ignore_errors' => true, | |
] | |
]; | |
$response = file_get_contents(getenv('SLACK_WEBHOOK_URL'), false, stream_context_create($opts)); | |
if($response !== 'ok') { | |
var_dump($http_response_header); // dump headers | |
var_dump($response); // dump body as well (usually where the problem can be found) | |
throw new \Exception("Unable to post to slack"); | |
} | |
} | |
post_slack_message('hi there'); |
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
function post_slack_message_styled($msg) { | |
$opts = [ | |
'http' => [ | |
'method' => 'POST', | |
'header' => "Content-type: application/json\r\n", | |
'content' => json_encode([ | |
'text' => $msg, | |
]), | |
'ignore_errors' => true, | |
] | |
]; | |
$response = file_get_contents(getenv('SLACK_WEBHOOK_URL'), false, stream_context_create($opts)); | |
if($response !== 'ok') { | |
var_dump($http_response_header); // dump headers | |
var_dump($response); // dump body as well (usually where the problem can be found) | |
throw new \Exception("Unable to post to slack"); | |
} | |
} | |
post_slack_message_styled('hi there'); |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment