How to post a message on Slack in PHP? [Full Guide]

I rarely small tutorials on developing part but that I have been asked by many of you in my small survey. I decided to share with you today a small piece of PHP code to send a message to a channel Slack easily with CURL. Let’s find out together!

For those who do not know, Slack is a collaborative software mainly used by business that allows to discuss projects of discuss with colleagues and many other things. I use it for myself every day at work, but not only. It can be an interesting solution for example to group various notifications!

So we’ll see how to post a message in a channel Slack in PHP.

Create webhook on Slack

First, you have to generate a URL linked to a channel to post in it, it’s called a webhook . This requires going into the top left menu (by clicking on the name of your Slack) and then in “Apps & integrations ” and “ Manage ” (top right ). Click “ Customs integrations ” and then you will arrive on a page similar to this one.


All you need to choose your channel and you get a URL similar to this one.

Sending message via CURL in PHP

We now turn to the part that will send the message via the PHP CURL function. It really is not complicated, you’ll see, it’s simple.

First, we define the parameters that will go to settings and then sends all in CURL. In the settings, you can set: the channel in question, the username will appear on post desired (which may take PHP variables) and a small emoji !

  // We define our parameters$ Data = "payload =". json_encode (array ("Channel" => "#blog""Username" => "Antoine""Text" => 'New article on the blog of Antoine Guilbert'"Icon_emoji '=>': gift '   ));// Is sent via the above URL recovered$ Ch = curl_init ( "");curl_setopt ($ ch, CURLOPT_CUSTOMREQUEST, "POST");curl_setopt ($ ch, CURLOPT_POSTFIELDS, $ data);curl_setopt ($ ch, CURLOPT_RETURNTRANSFER, true);$ Result = curl_exec ($ ch);curl_close ($ ch);  

This is quite handy if you want to be notified when someone submits a form, registers for a newsletter, or to go for PHP errors (thank you @gdebrion ). There are plenty of uses and I really thought it was a nice little thing and quick to set up!


If you have questions for the implementation, feel free in the comments. I tested it and normally everything is ok!

No comments:

Powered by Blogger.