Sending files to the Telegram Bot API in PHP: cURL, file_id, URL, and size limits

When developing Telegram bots for businesses, there is often a need to send media content to users: invoices in PDF format, receipts, photos of products, certificates, or report exports. The Telegram Bot API provides three main ways to transfer files in the methods sendPhoto, sendDocument, sendVideo and others: binary upload via multipart/form-dataSubmission file_id previously uploaded object and sending a direct HTTP link.

Each of these approaches has its own limitations, performance pitfalls, and use cases. In this article, we will take a detailed look at the implementation of all three methods in pure PHP using cURL and learn how to cache. file_id and handle API errors correctly.

Methods of file transfer and limits of the Telegram Bot API

Before writing code, it's important to clearly understand the technical limitations of the Telegram Bot API. Choosing the wrong transmission method can lead to errors. 400 BAD_REQUEST or significant delays in the bot's response.

  • Direct upload (multipart/form-data): allows you to upload files from your server. The file size limit for the standard Bot API is 50MB. For documents 10 MB for photos. If you use your own instance of the Local Bot API Server, this limit increases to 2000 MB (2 GB).
  • Sending file_id: the fastest and most economical way. The file is already on Telegram servers, so only a short text identifier is transmitted. The size limit is only restricted by the original file (up to 2 GB). Sending is instantaneous and does not use up your server's incoming/outgoing traffic.
  • Sharing a public URL: Telegram downloads the file itself using your HTTP/HTTPS link. However, the strictest limits apply here: the maximum file size for Telegram to download via URL is 20 MB For documents 5 MB for photos. In addition, the Telegram server must have direct access to the file without CAPTCHAs, basic authentication, and with a valid SSL certificate.

Uploading a local file via multipart/form-data using cURL

When a file is generated "on the fly" (for example, a PDF invoice via Dompdf or TCPDF) or uploaded by the client from the admin panel, it must be sent to Telegram as an initial upload. To do this, we will create a request multipart/form-data with the help of the class CURLFile.

Use file_get_contents() for making requests to the Telegram API is unacceptable for several reasons: the inability to flexibly configure timeouts, the lack of proper reading of HTTP statuses for 4xx/5xx errors, and problems with transmitting long binary data.

<?php

/**
* Отправка локального документа в Telegram через multipart/form-data
*
* @param string $chatId Идентификатор чата получателя
* @param string $filePath Абсолютный путь к файлу на сервере
* @param string $caption Подпись к файлу (опционально)
* @return array Массив result из ответа Telegram API
* @throws RuntimeException При ошибках cURL или Telegram API
*/
function sendTelegramDocument(string $chatId, string $filePath, string $caption = ''): array
{
$token = getenv('TELEGRAM_BOT_TOKEN');
if (!$token) {
throw new RuntimeException('Переменная окружения TELEGRAM_BOT_TOKEN не задана');
}

if (!file_exists($filePath) || !is_readable($filePath)) {
throw new InvalidArgumentException("Файл не найден или недоступен для чтения: {$filePath}");
}

$mimeType = mime_content_type($filePath) ?: 'application/octet-stream';

$postData = [
'chat_id' => $chatId,
'document' => new CURLFile($filePath, $mimeType, basename($filePath)),
'caption' => $caption,
'parse_mode' => 'HTML',
];

$url = "https://api.telegram.org/bot{$token}/sendDocument";

$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => $url,
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => $postData,
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 60,
CURLOPT_CONNECTTIMEOUT => 10,
]);

$response = curl_exec($ch);
$curlError = curl_error($ch);
$httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($response === false) {
throw new RuntimeException("cURL ошибка при отправке файла: {$curlError}");
}

$data = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE) {
throw new RuntimeException('Ошибка парсинга JSON ответа Telegram API: ' . json_last_error_msg());
}

if ($httpCode !== 200 || empty($data['ok'])) {
$description = $data['description'] ?? 'Неизвестная ошибка';
$errorCode = $data['error_code'] ?? $httpCode;
throw new RuntimeException("Telegram API Error [{$errorCode}]: {$description}");
}

return $data['result'];
}

Reuse file_id to speed up sending

Resend the same file (for example, a public offer, price list, or instructions) via multipart/form-data with every user request — a common architectural mistake. This puts a strain on the network, slows down the bot, and reaches the limits of bandwidth.

When a document or photo is sent for the first time, Telegram returns a unique file_id. By keeping this file_id to the database, all subsequent submissions of this document can be made through a regular JSON request without reloading the binary content.

First, let's write a universal function for sending media via file_id or URL via JSON payload:

<?php

/**
* Отправка медиафайла по file_id или URL через application/json
*
* @param string $method Метод API (sendPhoto, sendDocument и т.д.)
* @param string $chatId Идентификатор чата
* @param string $fileIdentifier Уникальный file_id или публичный URL
* @param string $caption Подпись к медиа
* @return array Результат запроса
*/
function sendTelegramMediaByIdOrUrl(string $method, string $chatId, string $fileIdentifier, string $caption = ''): array
{
$token = getenv('TELEGRAM_BOT_TOKEN');
if (!$token) {
throw new RuntimeException('Переменная TELEGRAM_BOT_TOKEN не задана');
}

$paramName = ($method === 'sendPhoto') ? 'photo' : 'document';

$payload = [
'chat_id' => $chatId,
$paramName => $fileIdentifier,
'caption' => $caption,
'parse_mode' => 'HTML',
];

$ch = curl_init();
curl_setopt_array($ch, [
CURLOPT_URL => "https://api.telegram.org/bot{$token}/{$method}",
CURLOPT_POST => true,
CURLOPT_POSTFIELDS => json_encode($payload),
CURLOPT_HTTPHEADER => ['Content-Type: application/json'],
CURLOPT_RETURNTRANSFER => true,
CURLOPT_TIMEOUT => 15,
CURLOPT_CONNECTTIMEOUT => 5,
]);

$response = curl_exec($ch);
$curlError = curl_error($ch);
$httpCode = (int)curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);

if ($response === false) {
throw new RuntimeException("cURL ошибка: {$curlError}");
}

$data = json_decode($response, true);
if (json_last_error() !== JSON_ERROR_NONE || $httpCode !== 200 || empty($data['ok'])) {
$desc = $data['description'] ?? $curlError ?? 'HTTP ' . $httpCode;
throw new RuntimeException("Ошибка отправки по file_id/URL: {$desc}");
}

return $data['result'];
}

Now let's set up hybrid logic: we check for the presence of a saved item. file_id in the database. If it's there, we send it instantly. If it's not there or Telegram returned an error (for example, file_id became invalid when the bot was changed), we perform the initial upload of the file and save the new one file_id In DB

<?php

/**
* Гибридная отправка документа с кэшированием file_id в MySQL/PostgreSQL
*/
function sendPriceList(PDO $db, string $chatId, string $localFilePath, string $documentKey): string
{
// 1. Пытаемся достать file_id из БД
$stmt = $db->prepare('SELECT file_id FROM telegram_files WHERE document_key = :key LIMIT 1');
$stmt->execute([':key' => $documentKey]);
$cachedFileId = $stmt->fetchColumn();

if ($cachedFileId) {
try {
sendTelegramMediaByIdOrUrl('sendDocument', $chatId, $cachedFileId, 'Актуальный прайс-лист');
return $cachedFileId;
} catch (RuntimeException $e) {
// Фолбэк: если file_id устарел или сброшен, переходим к загрузке файла
}
}

// 2. Первичная загрузка через multipart/form-data
$result = sendTelegramDocument($chatId, $localFilePath, 'Актуальный прайс-лист');
$newFileId = $result['document']['file_id'];

// 3. Сохраняем полученный file_id в базу для последующих пользователей
$saveStmt = $db->prepare('
INSERT INTO telegram_files (document_key, file_id, created_at)
VALUES (:key, :file_id, NOW())
ON DUPLICATE KEY UPDATE file_id = VALUES(file_id)
');
$saveStmt->execute([
':key' => $documentKey,
':file_id' => $newFileId,
]);

return $newFileId;
}

Sending a File via URL: When It's Convenient and What Are the Risks?

Providing an external URL is justified if the files are already stored on a CDN or in S3-compatible storage (Selectel, MinIO, AWS S3), and you don't want to first download them to your PHP server to forward them to Telegram.

However, keep in mind the critical risks when working with URLs:

  1. Timeouts and blocks: Telegram downloads the file from its servers. If your CDN blocks Telegram's IP ranges or delivers content slowly, the request will fail. 400 BAD_REQUEST: wrong file identifier/HTTP URL specified.
  2. Hard limit of 20 MB: If the document at the link exceeds 20 MB (or the photo is >5 MB), Telegram will refuse to process it.
  3. Lack of control over MIME types: Telegram determines the file type based on the HTTP header Content-Typeserved by your web server. If the CDN serves Text / HTML instead application/pdf, the file will be sent with a corrupted extension.

Comparison of sendPhoto and sendDocument

Developers often confuse the purposes of methods. sendPhoto And sendDocument. The main differences lie in the compression and processing of metadata:

  • sendPhoto: Telegram automatically compresses the image, removes EXIF metadata, and adjusts it to the optimal resolution for quick display in the chat grid. Perfect for product catalogs and previews.
  • sendDocument: Transfers the file "as is", without quality compression and retaining the original file name. Ideal for documents, scans, and photos in original quality (to do this, you need to transfer photos via sendDocument).

Correct choice of method and combination CURLFile With caching file_id allow you to create reliable Telegram bots capable of handling thousands of media requests per minute without overloading the server.

If you need professional integration of a Telegram bot with your CRM, web service, or automation of complex sales funnels, the specialists at BotCreator will help you implement a project of any complexity.

New articles on Telegram

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