Codebusters

Post to a Discord Webhook from PHP: One File, No Composer (Tested)

Wednesday 2 December 2026

Sometimes an email is too slow and too easy to ignore, and a message in a chat channel is what you want. Discord lets you post to a channel with one HTTP request, so no bot, no library and no Composer. Here is a single PHP file that does it, plus the two things that usually break it: messages over 2,000 characters and rate limiting. I ran every case below on PHP 8.4.28 against a local stand-in for Discord, and I say what that does and does not prove at the end.

The code

<?php
// Post a message to a Discord webhook with plain cURL. No Composer.
// Returns true on success, false on failure (and logs why).

function discord_send(string $webhookUrl, string $text, string $username = 'Monitor'): bool
{
    // Discord rejects content over 2000 characters, so split long text.
    foreach (str_split($text, 1900) as $chunk) {
        if (!discord_post($webhookUrl, [
            'username'         => $username,
            'content'          => $chunk,
            'allowed_mentions' => ['parse' => []],   // never ping @everyone by accident
        ])) {
            return false;
        }
    }
    return true;
}

function discord_post(string $webhookUrl, array $payload, int $maxTries = 3): bool
{
    for ($try = 1; $try <= $maxTries; $try++) {
        $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_CONNECTTIMEOUT => 5,
            CURLOPT_TIMEOUT        => 10,
        ]);
        $body = curl_exec($ch);
        $code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
        $err  = curl_error($ch);
        curl_close($ch);

        if ($code === 204 || ($code >= 200 && $code < 300)) {
            return true;                              // 204 No Content is success
        }
        if ($code === 429) {                          // rate limited: wait as told, then retry
            $wait = (float) (json_decode((string) $body, true)['retry_after'] ?? 1);
            error_log("discord: 429, waiting {$wait}s (try $try of $maxTries)");
            usleep((int) (min($wait, 30) * 1000000));
            continue;
        }
        error_log("discord: HTTP $code $err " . substr((string) $body, 0, 200));
        return false;                                 // anything else: log and carry on
    }
    return false;
}

How to use it

Create a webhook in the settings of the channel you want to post to, and keep its URL in a config file outside your web root (anyone who has that URL can post to your channel, so treat it like a password). Then call it from a cron script:

require __DIR__ . '/discord.php';
$webhook = trim(file_get_contents('/path/to/discord-webhook.txt'));
discord_send($webhook, 'Stream is back up', 'Stream monitor');

What each part is for

  • Success is 204. Discord’s documentation says the execute-webhook call returns a message or 204 No Content depending on the wait query parameter, and it is false by default, so a plain POST comes back with 204 and an empty body. The code treats any 2xx as success.
  • The 2,000 character limit. The documented limit for content is 2000 characters. discord_send() splits at 1,900 so a long error log goes out as several messages (splitting at a fixed length can cut a line in half, which is fine for an alert).
  • Rate limits. Over the limit, Discord replies with HTTP 429 and a JSON body whose retry_after field says how many seconds to wait. The code waits that long and tries again, up to 3 times, with a 30 second cap.
  • allowed_mentions. Discord’s documentation warns about unexpected mentions when you pass user-generated text, so the empty parse list means nothing in the text can ping a role or everyone.
  • Timeouts. 5 seconds to connect and 10 to finish, so a Discord outage cannot hang your cron job.

What I tested

Terminal output of the Discord webhook test: short message true, rate limited true after 0.5 seconds, 5,000 characters true, bad webhook false, raw 2,500 characters false

I wrote a tiny PHP server that answers like Discord for the cases that matter: 204 for a normal post, a 429 with retry_after of 0.5 on the first request to one path, a 404 Unknown Webhook for a deleted webhook, and a 400 for any content over 2,000 characters. The results:

  1. A 17 character message was sent in one request.
  2. The rate-limited call got its 429, waited 0.5 seconds and then succeeded on the second try.
  3. 5,000 characters of text became three requests of 1,900, 1,900 and 1,200 characters, and all succeeded.
  4. A deleted webhook returned false and logged the 404 without any retries (so no repeated spam to a dead URL).
  5. Sending 2,500 characters directly with discord_post(), skipping the splitting, got the 400 and false.
  6. With nothing listening on the port, it returned false straight away.

What I did not test

This was a stand-in I wrote, not live Discord, so it proves my handling of the documented responses and says nothing about Discord’s real rate limits or its message formatting. I have not tried embeds, files, or webhooks that post into forum channels, which Discord’s documentation says need a thread name or ID. If you are sending an alert from cron, pair this with the state-file trick in Cron alert spamming you? How to make it email once, or you will find out how many messages a minute-by-minute monitor can send (the 2,000 character limit is the least of your worries!).