Posting to Slack with PHP

Posting to Slack with PHP is incredibly quick and easy, here is how you can

Sending messages to Slack using PHP couldn’t be easier. I think a lot of people assume it is going to be harder than it is.

There are two steps.

Get your Slack webhook

In Slack go the the channel you want your webhook to feed into and from the menu select “Configure Integrations”

Select “Incoming Webhooks” as the integration you want to add.

Give the webhook a name and copy down the webhook URL. It will be something like https://hooks.slack.com/services/xxx/yyy/zzz.

Use curl to send to the webhook

Now for the PHP code;

  // Create a constant to store your Slack URL
  define('SLACK_WEBHOOK', 'https://hooks.slack.com/services/xxx/yyy/zzz');
  // Make your message
  $message = array('payload' => json_encode(array('text' => 'My Message')));
  // Use curl to send your message
  $c = curl_init(SLACK_WEBHOOK);
  curl_setopt($c, CURLOPT_SSL_VERIFYPEER, false);
  curl_setopt($c, CURLOPT_POST, true);
  curl_setopt($c, CURLOPT_POSTFIELDS, $message);
  curl_exec($c);
  curl_close($c);

When this code runs it will update Slack with “My Message”.

Like all code, this could be improved. I wanted to share the most simple implementation.

Not a lot of lines of code to add some really useful functionality into your Slack channel!

Thanks to Jordan Klosterman for spotting a typo in the code, my $message assignment was invalid.

Recent posts View all

SEOInterviews

WebLinkR Interview - we spoke with SEO Reddit Mod WebLinkR about, well, SEO

A short interview with SEO Reddit Mod WebLinkR about some of their SEO thinking.

Productivity Web Dev

81% of people more wary of dependencies due to AI

We polled people about how they felt about software dependenices since more folk used AI