Sending sendMessage in Telegram via cURL in PHP: HTML Escaping, Timeouts, and 3-Tier Error Handling

Sending messages via the Telegram Bot API seems like a trivial task until the first production outage. The connection hangs at the network handshake stage, a user enters the < or & character causing Telegram to reject the entire packet, or the server returns 429 Too Many Requests while the script silently terminates without logging.

Using the built-in file_get_contents function to work with the Telegram API is a common mistake. It does not allow flexible timeout configuration, loses HTTP response headers on 4xx/5xx errors, and throws PHP warnings. For fault-tolerant systems, the standard tool remains the cURL extension combined with strict validation at each stage of request execution.

Safe HTML Markup Preparation for sendMessage

The Telegram Bot API supports a limited subset of HTML tags: <b>, <i>, <a>, <code>, <pre>, and a few others. If an unclosed tag or unescaped special characters (for instance, raw input from a website's HTML form) are passed in the parse_mode = 'HTML' parameter, Telegram will return a 400 Bad Request: can't parse entities error, and the message will not be delivered.

The htmlspecialchars() function in PHP escapes quotes, ampersands, and angle brackets by default. To construct dynamic text, you must escape all user variables BEFORE inserting them into the final HTML template.

<?php

declare(strict_types=1);

/**
* Экранирует произвольный текст для безопасной вставки в parse_mode HTML.
*/
function escapeTelegramHtml(string $text): string
{
return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML5, 'UTF-8');
}

// Пример подготовки динамического уведомления о лиде
$userName = 'Иван & Партнеры <Dev>';
$userComment = 'Интересует цена > 1000$';

$safeName = escapeTelegramHtml($userName);
$safeComment = escapeTelegramHtml($userComment);

// Шаблон содержит валидные HTML-теги, а переменные экранированы
$messageText = "<b>Новая заявка!</b>
";
$messageText .= "Имя: <i>{$safeName}</i>
";
$messageText .= "Коммент: <code>{$safeComment}</code>";

// Результат безопасен для отправки с parse_mode=HTML

Configuring the cURL Request and Timeout Management

When sending notifications from a synchronous web request, limiting the connection and response waiting times is critically important. If the Telegram API is temporarily unavailable or routing issues occur, the lack of timeouts will lead to exhaustion of FPM/Nginx workers.

Working with the Telegram API requires two timeouts:

  • CURLOPT_CONNECTTIMEOUT — maximum waiting time to establish a TCP/TLS connection (typically 3–5 seconds).
  • CURLOPT_TIMEOUT — overall execution time of the entire HTTP request (typically 5–10 seconds).

All parameters are sent via the POST method in JSON or application/x-www-form-urlencoded format. Passing JSON in the body of a POST request guarantees correct processing of special characters and UTF-8 strings without urlencode issues.

3-Tier Validation of Telegram API Response

Reliable response processing should go through three sequential validation stages:

  1. Network level (cURL): Checking curl_errno(). DNS errors, timeouts, and TLS connection drops are handled at this step.
  2. HTTP protocol level: Checking the status code via CURLINFO_HTTP_CODE. 200 codes indicate success or a valid API response. 4xx/5xx codes indicate authentication issues, rate limits, or Telegram server failures.
  3. Application level (Telegram JSON): Decoding the response body via json_decode(), checking json_last_error(), and verifying the logical flag $responseData['ok'] === true.
<?php

declare(strict_types=1);

/**
* Выполняет POST-запрос к Telegram Bot API через cURL с 3 уровнями проверок.
*
* @param string $method Метод Bot API (например, sendMessage)
* @param array $payload Массив параметров метода
* @return array Декодированный массив ответа от Telegram
* @throws RuntimeException При сетевых ошибках или ошибках Telegram API
*/
function sendTelegramApiRequest(string $method, array $payload): array
{
$botToken = getenv('TELEGRAM_BOT_TOKEN');
if (!$botToken) {
throw new RuntimeException('Токен TELEGRAM_BOT_TOKEN не задан в окружении');
}

$url = "https://api.telegram.org/bot{$botToken}/{$method}";

$ch = curl_init();

$jsonPayload = json_encode($payload, JSON_UNESCAPED_UNICODE);
if ($jsonPayload === false) {
throw new RuntimeException('Ошибка кодирования JSON payload: ' . json_last_error_msg());
}

curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $jsonPayload,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
'Accept: application/json',
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 4,
CURLOPT_TIMEOUT => 8,
CURLOPT_SSL_VERIFYPEER => true,
]);

$rawResponse = curl_exec($ch);
$curlErrno = curl_errno($ch);
$curlError = curl_error($ch);
$httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

// Уровень 1: Ошибка транспортного слоя cURL
if ($curlErrno !== 0) {
throw new RuntimeException("cURL ошибка [{$curlErrno}]: {$curlError}");
}

// Уровень 2: Проверка ответа на корректный JSON
$data = json_decode((string) $rawResponse, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException(
"Некорректный JSON от Telegram API (HTTP {$httpCode}): " . json_last_error_msg()
);
}

// Уровень 3: Проверка ответа от бизнес-логики Telegram (ok: false)
if (!isset($data['ok']) || $data['ok'] !== true) {
$errorCode = $data['error_code'] ?? $httpCode;
$description = $data['description'] ?? 'Неизвестная ошибка Telegram API';

// Анализ дополнительных параметров (например, retry_after)
$retryAfter = $data['parameters']['retry_after'] ?? null;
$extraInfo = $retryAfter ? " (Retry after {$retryAfter}s)" : '';

throw new RuntimeException(
"Telegram API error [{$errorCode}]: {$description}{$extraInfo}"
);
}

return $data;
}

Complete Working Example: TelegramNotifier Service Class

Let's combine safe HTML formatting, the cURL call, and validation into a dedicated service layer class. The class accepts a chat ID, builds the message, and handles specific error scenarios.

<?php

declare(strict_types=1);

namespace App\Services;

use RuntimeException;

class TelegramNotifier
{
private string $botToken;

public function __construct(?string $botToken = null)
{
$token = $botToken ?? getenv('TELEGRAM_BOT_TOKEN');
if (!$token) {
throw new RuntimeException('Не указан токен Telegram бота.');
}
$this->botToken = $token;
}

/**
* Отправляет текстовое сообщение с HTML-разметкой в чат.
*
* @param int|string $chatId
* @param string $text Raw текст или сформированный HTML
* @param array $extraOptions Дополнительные параметры (reply_markup и т.д.)
* @return array Результат ответа от Telegram
*/
public function sendMessage(int|string $chatId, string $text, array $extraOptions = []): array
{
$payload = array_merge([
'chat_id' => $chatId,
'text' => $text,
'parse_mode' => 'HTML',
'disable_web_page_preview' => true,
], $extraOptions);

return $this->request('sendMessage', $payload);
}

/**
* Экранирует произвольные пользовательские данные.
*/
public static function escape(string $text): string
{
return htmlspecialchars($text, ENT_QUOTES | ENT_SUBSTITUTE | ENT_HTML5, 'UTF-8');
}

private function request(string $method, array $payload): array
{
$url = "https://api.telegram.org/bot{$this->botToken}/{$method}";
$ch = curl_init();

$jsonPayload = (string) json_encode($payload, JSON_UNESCAPED_UNICODE);

curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $jsonPayload,
CURLOPT_HTTPHEADER => [
'Content-Type: application/json',
],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_CONNECTTIMEOUT => 3,
CURLOPT_TIMEOUT => 6,
]);

$response = curl_exec($ch);
$errno = curl_errno($ch);
$error = curl_error($ch);
$httpCode = (int) curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($errno !== 0) {
throw new RuntimeException("cURL error ({$errno}): {$error}");
}

$decoded = json_decode((string) $response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException("JSON decode error: " . json_last_error_msg());
}

if (!is_array($decoded) || !($decoded['ok'] ?? false)) {
$desc = $decoded['description'] ?? 'Unknown API error';
$code = $decoded['error_code'] ?? $httpCode;
throw new RuntimeException("Telegram API Error [{$code}]: {$desc}");
}

return $decoded;
}
}

// Пример использования класса:
try {
$notifier = new TelegramNotifier();

$customerName = self::escape('ООО "Вектор & Ко"');
$orderId = 48291;

$htmlText = "<b>Новый заказ #{$orderId}</b>
";
$htmlText .= "Клиент: <code>{$customerName}</code>";

$response = $notifier->sendMessage(
chatId: -100123456789, // ID группы или чата
text: $htmlText
);

// Доступ к message_id созданного сообщения
$messageId = $response['result']['message_id'];
} catch (RuntimeException $e) {
// Логирование ошибки в файл или Sentry
error_log("Не удалось отправить сообщение в Telegram: " . $e->getMessage());
}

429 Too Many Requests and 400 Bad Request Errors

During active broadcasting or sending high-frequency messages to chats, Telegram may return status 429 Too Many Requests. The response body will contain a parameters object with a retry_after value (the time in seconds to wait before repeating the request):

The Telegram Bot API limits message sending to 30 messages per second across different users and up to 1 message per second to a specific group or direct chat.

If the server returns a 429 error, the script must read the $data['parameters']['retry_after'] value and pause sending (or return the task to the queue with a delay of delay = retry_after). Do not attempt to resend the request immediately in a while(true) loop without a pause — this will lead to a temporary or permanent block of the bot's IP address.

If you are developing complex integrations that require handling broadcast messaging, Mini Apps, or CRM systems, contact the specialists at BotCreator to design a fault-tolerant Telegram bot architecture.

New articles on Telegram

We explain what to automate in your business and how it works in practice. No spam.