Skip to content

Instantly share code, notes, and snippets.

@xcsrz
Last active September 18, 2023 17:32
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save xcsrz/29958f2ab7bae24b21b106c933dc8d22 to your computer and use it in GitHub Desktop.
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
<?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');
<?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