PHP

Slack Incoming-Webhook Notification

admin by @admin ADMIN
1h ago
May 31, 2026
Public
0 0 up · 0 down Sign in to vote
Fire a quick notification to a Slack channel via an incoming webhook URL. Includes basic markdown-style mentions and an attachment color for severity.
PHP
Raw
<?php
function slackNotify(string $webhookUrl, string $text, string $color = '#36a64f', ?string $channel = null): bool {
    $payload = ['attachments' => [[
        'text'  => $text,
        'color' => $color,         // green / yellow / red
        'mrkdwn_in' => ['text'],
    ]]];
    if ($channel) $payload['channel'] = $channel;

    $ch = curl_init($webhookUrl);
    curl_setopt_array($ch, [
        CURLOPT_POST           => true,
        CURLOPT_POSTFIELDS     => json_encode($payload),
        CURLOPT_HTTPHEADER     => ['Content-Type: application/json'],
        CURLOPT_RETURNTRANSFER => true,
        CURLOPT_TIMEOUT        => 5,
    ]);
    $resp = curl_exec($ch);
    $code = curl_getinfo($ch, CURLINFO_RESPONSE_CODE);
    curl_close($ch);
    return $code === 200 && $resp === 'ok';
}

slackNotify('https://hooks.slack.com/services/T0/B0/XXXX', ':rotating_light: *Deploy failed* on prod', '#dc2626');
Tags

Save your own code snippets

Create a free account and build your private vault. Share publicly whenever you want.