Trying to send messages to slack
channels with incoming webhooks
installed on them. Attachments
needs to be sent along with the message and PHP variables holds these URLs. Similary, I want to send some ID's
which are again hold in some PHP variables. Here is my server side PHP
code:
<?php
$testplan_name = $_POST[plan]; //test plan name coming from the client
$url1 = $_POST[run_url]; //run url coming from the client
$url2 = $_POST[plan_url]; //plan url coming from the client
$room = "random";
$icon_url = ":ghost:";
$username = "Test";
$attachments = array([
'fallback' => 'Hey! See this message',
'pretext' => 'Here is the plan name ${testplan_name}',
'color' => '#ff6600',
'fields' => array(
[
'title' => 'Run URL',
'value' => 'url1',
'short' => true
],
[
'title' => 'Build URL',
'value' => 'url2',
'short' => true
]
)
]);
$data = "payload=" . json_encode(array(
"channel" => "#{$room}",
"icon_emoji" => $icon_url,
"username" => $username,
"attachments" => $attachments
));
$url = "https://hooks.slack.com/services/XXXX/XXX/XXXXXXXXXXXXX"; //got from slack as a webhook URL
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
$result = curl_exec($ch);
echo var_dump($result);
if($result === false)
{
echo 'Curl error: ' . curl_error($ch);
}
curl_close($ch);
If you see in the attachments
variable above, there is variable inside of pretext
which tries to print the value of ${testplan_name}
declared at the top. However, it does not seem to work and the program is failed to post messages to slack channels. Similarly, I want to print values of url1
and url2
in the attachments -> fields
values as can be seen above(the way I am trying to print). The program just works fine if I do not try to use any variables and get their values while posting messages. How do I print the values of these variables in messages?
(slack is a messaging platform for teams, if you don't know)
Try this instead>
$attachments = array([
'fallback' => 'Hey! See this message',
'pretext' => 'Here is the plan name '.$testplan_name,
'color' => '#ff6600',
'fields' => array(
[
'title' => 'Run URL',
'value' => $url1,
'short' => true
],
[
'title' => 'Build URL',
'value' => $url2,
'short' => true
]
)
]);