Prevent cURL Timeout Crashes When Uploading Media in PHP Telegram Bots

Imagine building a automated PDF invoice bot or a digital badge generator for event attendees. Every time a user clicks Download Receipt, your backend generates a document on disk and dispatches it through Telegram's sendDocument endpoint.

At first, testing in single-user local development works fine. But in production, users report frozen buttons and missed updates. When multiple users request documents simultaneously, your webhook handlers start failing with 504 Gateway Timeout errors. Behind the scenes, your backend is spending seconds re-uploading the exact same multi-megabyte static files or failing silently because raw file paths were passed into cURL without proper multipart/form-data formatting.

If you handle Telegram media uploads naively in PHP, you hit memory limits, exhaust webhook execution timeouts, and waste bandwidth. This guide walks through constructing robust media delivery in PHP using CURLFile, handling API error payloads, and implementing a strict file_id caching pipeline.

The Flawed Approach: Uploading Disk Files on Every Request

When developers attempt to send files using Telegram's API in PHP, they frequently make two major mistakes: relying on string file paths in raw array payloads, or re-uploading identical media assets over cURL every single time a webhook triggers.

Passing a file path like ['document' => '/var/www/files/report.pdf'] inside a standard JSON request payload to https://api.telegram.org/bot<token>/sendDocument sends a literal string, not the file contents. Telegram responds with a 400 Bad Request: wrong file identifier/HTTP URL specified error.

Even when developers correctly switch to multipart/form-data, sending the file from local storage on every incoming request creates an operational bottleneck:

// FAILED PATTERN: Re-uploading a static 8MB manual on every webhook call
$telegramUrl = "https://api.telegram.org/bot" . getenv('BOT_TOKEN') . "/sendDocument";

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $telegramUrl);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'chat_id' => $chatId,
'document' => new CURLFile('/var/www/app/assets/user_manual.pdf')
]);
// Missing timeouts, missing HTTP status checks, missing response parsing!
$result = curl_exec($ch);
curl_close($ch);

This pattern exposes your application to three severe failure modes: 1. Webhook Blocking: Telegram expects your webhook endpoint to return a 200 OK response within a few seconds. Uploading an 8MB file over a standard server network interface takes time. Under concurrent load, PHP-FPM worker pools saturate, and Telegram drops incoming webhooks. 2. Resource Exhaustion: Uploading files continuously burns server bandwidth and CPU cycles unnecessarily. 3. Unhandled API Errors: If the uploaded file exceeds size limits (50 MB for documents, 5 MB for photos via standard API calls), Telegram returns an ok: false JSON payload with a 413 Payload Too Large or 400 Bad Request. Ignoring cURL HTTP status codes leaves your app unaware that the delivery failed.

Implementing a Secure Multipart cURL Client

To handle file uploads safely, you need a resilient HTTP wrapper. This wrapper must accept CURLFile instances, set explicit execution timeouts, parse the returned JSON payload, and verify both cURL-level errors and Telegram API error states.

Create a dedicated client function for executing Telegram Bot API requests:

<?php

declare(strict_types=1);

/**
* Sends a request to the Telegram Bot API with full status checking.
*
* @param string $method The API method (e.g., 'sendDocument', 'sendPhoto')
* @param array $payload Key-value parameters, including scalar values or CURLFile objects
* @return array The decoded Telegram response array
* @throws Exception If cURL fails or Telegram returns an error payload
*/
function sendTelegramRequest(string $method, array $payload): array
{
$botToken = getenv('BOT_TOKEN');
if (!$botToken) {
throw new RuntimeException('BOT_TOKEN environment variable is missing.');
}

$url = sprintf('https://api.telegram.org/bot%s/%s', $botToken, $method);

$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $payload);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 5);
curl_setopt($ch, CURLOPT_TIMEOUT, 30); // Prevent hanging processes

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

if ($curlErrno !== 0) {
throw new RuntimeException(sprintf('cURL execution failed: [%d] %s', $curlErrno, $curlError));
}

if ($responseBody === false || $responseBody === '') {
throw new RuntimeException('Received empty response body from Telegram API.');
}

$decoded = json_decode((string) $responseBody, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException('Failed to parse Telegram JSON response: ' . json_last_error_msg());
}

if (!isset($decoded['ok']) || $decoded['ok'] !== true) {
$description = $decoded['description'] ?? 'Unknown error';
$errorCode = $decoded['error_code'] ?? $httpCode;
throw new RuntimeException(sprintf('Telegram API Error [%d]: %s', $errorCode, $description));
}

return $decoded;
}

Notice how CURLOPT_POSTFIELDS accepts a flat array containing CURLFile objects. When cURL detects a CURLFile instance inside the array, it automatically switches the request content type to multipart/form-data and streams the file binary correctly.

Now wrap this request engine into a specialized media-dispatching function that validates MIME types and local file boundaries before attempting the network call:

/**
* Safely dispatches a local document file to a Telegram chat.
*
* @param int $chatId
* @param string $absoluteFilePath
* @param string $caption
* @return array The sent Message object payload from Telegram
*/
function sendLocalDocument(int $chatId, string $absoluteFilePath, string $caption = ''): array
{
if (!file_exists($absoluteFilePath) || !is_readable($absoluteFilePath)) {
throw new InvalidArgumentException(sprintf('File not found or unreadable: %s', $absoluteFilePath));
}

$fileSize = filesize($absoluteFilePath);
if ($fileSize === false || $fileSize > 50 * 1024 * 1024) { // 50MB Bot API limit
throw new InvalidArgumentException('File exceeds the 50MB Telegram Bot API limit.');
}

// Verify MIME type using finfo
$finfo = new finfo(FILEINFO_MIME_TYPE);
$mimeType = $finfo->file($absoluteFilePath) ?: 'application/octet-stream';
$postFileName = basename($absoluteFilePath);

$curlFile = new CURLFile($absoluteFilePath, $mimeType, $postFileName);

$payload = [
'chat_id' => $chatId,
'document' => $curlFile,
'caption' => htmlspecialchars($caption, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'),
'parse_mode' => 'HTML'
];

return sendTelegramRequest('sendDocument', $payload);
}

Caching and Reusing file_id Identifiers

When Telegram processes a media upload (sendDocument, sendPhoto, sendAudio, sendVideo), it processes the asset and returns a unique identifier string called a file_id inside the response object.

Instead of re-uploading the file on every user request, store this file_id in your database. Subsequent requests can pass the raw string file_id as the parameter value. Telegram will deliver the asset instantly from its internal servers without needing your server to send a single byte of file content.

Here is a complete production pattern demonstrating local file uploads, file_id persistence, and instant reuse using a PDO database storage layer:

<?php

declare(strict_types=1);

class TelegramMediaManager
{
private PDO $db;

public function __construct(PDO $db)
{
$this->db = $db;
}

/**
* Sends a document using a cached file_id if available, falling back to disk upload.
*/
public function sendDocumentCached(int $chatId, string $assetKey, string $localFilePath, string $caption = ''): void
{
// 1. Check database for existing file_id
$stmt = $this->db->prepare('SELECT telegram_file_id FROM media_cache WHERE asset_key = :key LIMIT 1');
$stmt->execute([':key' => $assetKey]);
$cachedFileId = $stmt->fetchColumn();

if ($cachedFileId && is_string($cachedFileId)) {
try {
// Attempt instant delivery using stored file_id string
sendTelegramRequest('sendDocument', [
'chat_id' => $chatId,
'document' => $cachedFileId,
'caption' => htmlspecialchars($caption, ENT_QUOTES | ENT_SUBSTITUTE, 'UTF-8'),
'parse_mode' => 'HTML'
]);
return;
} catch (RuntimeException $e) {
// If file_id is invalidated or stale, log and fall back to fresh upload
error_log("Failed sending cached file_id for key {$assetKey}: " . $e->getMessage());
}
}

// 2. Upload file via multipart/form-data if no cached file_id exists
$response = sendLocalDocument($chatId, $localFilePath, $caption);

// 3. Extract generated file_id from Telegram's response
$returnedFileId = $response['result']['document']['file_id'] ?? null;

if ($returnedFileId && is_string($returnedFileId)) {
// Save to database for future calls
$saveStmt = $this->db->prepare('
INSERT INTO media_cache (asset_key, telegram_file_id, created_at)
VALUES (:key, :file_id, NOW())
ON DUPLICATE KEY UPDATE telegram_file_id = VALUES(telegram_file_id)
');
$saveStmt->execute([
':key' => $assetKey,
':file_id' => $returnedFileId
]);
}
}
}

When to Use Public HTTPS URLs vs Local Files

Telegram also allows passing a publicly accessible HTTPS URL directly as the document or photo parameter (e.g. 'document' => 'https://example.com/files/terms.pdf'). Telegram's servers will download the file directly from your host.

Use this comparison matrix to decide which approach fits your workflow:

| Method | File Size Limit | Latency | Bandwidth Target | | :--- | :--- | :--- | :--- | | CURLFile (Multipart Upload) | 50 MB (Docs) / 10 MB (Photos) | High on first upload | Server uploads bytes directly | | file_id (Cached Reference) | 2 GB | Extremely fast (< 100ms) | Zero file upload bandwidth | | HTTPS URL | 20 MB (Docs) / 5 MB (Photos) | Medium (Telegram pulls URL) | Server serves external download |

*Rule of thumb:* Use HTTPS URLs for public dynamic media under 5MB. Use CURLFile for initial uploads of private, system-generated files. Always save and reuse file_id for any asset sent more than once.

Production Notes

- Unique file_id Properties: A file_id is unique to your bot. You cannot reuse a file_id obtained by Bot A inside Bot B's API calls. If you run multiple bots, scope your database cache key by bot_id. - File Expiry: While file_id strings generally persist long-term, Telegram occasionally invalidates them after backend structural updates. Always wrap file_id sends in a try/catch block to fall back to disk upload if Telegram returns a 400 Bad Request: wrong file identifier error. - Async Execution: Never generate large PDFs or execute slow CURLFile uploads directly inside your webhook execution path. Store incoming webhooks into a queue (such as Redis or RabbitMQ) and execute file generation and media dispatch inside an asynchronous PHP CLI background worker process.

Building dependable Telegram automation requires moving beyond simple script execution toward structured network handling and state management. For custom infrastructure setups, team extensions, or production-grade bot development, reach out to BotCreator — a specialized studio that builds high-performance Telegram bots and Mini Apps.

New articles on Telegram

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