Telegram BOT Api: how to send a photo using PHP?
When integrating the Telegram Bot API with PHP, handling image uploads often trips up developers who misunderstand how InputFile objects work under the hood. The official documentation states that the photo argument accepts either a String (a file_id) or an InputFile. This distinction is critical because it dictates not just the data format, but the HTTP method and headers required for the request to succeed.
If you attempt to resend an image already stored on Telegram's servers, passing a String is straightforward. You simply construct your URL like this:
$url = $bot_url . "sendPhoto?chat_id=" . $chat_id;
$post_fields = [
'photo' => 'PHOTO_FILE_ID_FROM_SERVER', // e.g., '401...:AQAD...'
'caption' => 'Here is a picture'
];
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, $post_fields);
curl_setopt($ch, CURLOPT_HTTPHEADER, []); // No special headers needed for file_id
$output = curl_exec($ch);
However, uploading a new image requires using multipart/form-data. This is where the confusion typically arises. The error message you encounteredâError: Bad Request: Wrong persistent file_id specifiedâindicates that the code attempted to pass a local file path as a string value within the POST body. Telegram's parser interprets this as an attempt to reuse an existing file_id, checks its format, finds it invalid (since a filesystem path is not a valid ID), and rejects the request immediately.
To upload a new file correctly, you must pass the local filepath directly to CURLOPT_POSTFIELDS without any prefixes like @/. While many PHP tutorials suggest using @filename to indicate a file upload in standard form submissions, the Telegram API documentation specifically notes that InputFile objects "must be posted using multipart/form-data in the usual way." In the context of cURL's CURLOPT_POSTFIELDS, passing just the filename is often sufficient for modern PHP versions to handle the boundary construction automatically.
Here is the corrected approach for uploading a new photo:
$bot_url = "https://api.telegram.org/bot<your_token>/";
$url = $bot_url . "sendPhoto?chat_id=" . $chat_id;
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
// Define the fields. Pass the filename directly without '@' prefix for cURL v7+ usually works best with boundaries handled automatically,
// OR use the @ syntax if your specific PHP version/curl setup requires explicit file handling flags.
// The most robust standard approach:
curl_setopt($ch, CURLOPT_POSTFIELDS, [
'photo' => '/root/dev/fe_new.png',
'caption' => 'Check out this new image' // Optional
]);
$output = curl_exec($ch);
$http_code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
if ($http_code === 200) {
$result = json_decode($output, true);
echo "Success: " . print_r($result, true);
} else {
echo "Failed with HTTP code: " . $http_code;
echo "Response: " . $output;
}
curl_close($ch);
A common pitfall occurs when developers try to bypass cURL's built-in file handling by using file_get_contents() to read the binary data into a string variable and then passing that raw content. While this works for generic API calls, Telegram's specific implementation for the InputFile object expects a stream or a direct file reference in the multipart body. Passing a raw base64-encoded string or raw bytes without proper boundary markers often results in an empty reply from the server, which can be misleading since cURL might report no error.
Another subtle issue involves the CURLOPT_INFILESIZE option shown in your initial attempt. While setting the size of the uploaded content is valid for some APIs, Telegram's specific endpoint handles file sizing internally based on the multipart stream length. Explicitly setting this flag can sometimes interfere with how cURL constructs the multipart boundaries, potentially leading to malformed requests if not calculated precisely against the final encoded body size.
When building production-ready bots, always verify the HTTP status code returned by curl_exec. A successful photo upload returns a JSON object containing the file ID of the newly uploaded image. If you receive an unexpected response, inspecting the raw $output string is more informative than relying solely on curl_error(), as Telegram's API often provides detailed error messages within the JSON body even when the HTTP status code is 400.
For complex applications where managing file streams manually becomes cumbersome, consider using a framework like Laravel. The LaravelCompany community often discusses robust patterns for handling media uploads, but regardless of the stack you choose, understanding that InputFile implies a multipart stream is the fundamental requirement for sending photos to Telegram.