Getting 502 Error When Sending Images Through Telegram Bot API

I’m trying to send an image file through the Telegram Bot API but keep running into issues. Here’s what I’m currently doing:

if(file_exists($_FILES['imageUpload']['tmp_name'])){
    $handle = fopen($_FILES['imageUpload']['tmp_name'], "rb");
    $fileData = fread($handle, $_FILES['imageUpload']['size']);
    fclose($handle);
    $httpClient = new Client();
    $result = $httpClient->post("https://api.telegram.org/bot[TOKEN]/sendPhoto", [
        'body' => ['chat_id' => '12345678', 'photo' => $fileData]
    ]);
    var_dump($result);
}else{
    echo("File not found");
}

The problem is I keep getting Nginx 502 Bad Gateway errors when trying to upload photos. Other API calls like getMe work perfectly fine, so my bot token and connection are good. Is there something wrong with how I’m formatting the request body or handling the file data? I’m using Guzzle version 5.3.0 for this project.

You’re using the wrong content type. Telegram Bot API needs multipart/form-data for file uploads, not a plain body array. Your current setup sends the raw file data wrong.

Try this with Guzzle:

$result = $httpClient->post("https://api.telegram.org/bot[TOKEN]/sendPhoto", [
    'multipart' => [
        [
            'name' => 'chat_id',
            'contents' => '12345678'
        ],
        [
            'name' => 'photo',
            'contents' => fopen($_FILES['imageUpload']['tmp_name'], 'r'),
            'filename' => $_FILES['imageUpload']['name']
        ]
    ]
]);

This formats the request as multipart data, which is what Telegram expects. The 502 error’s probably happening because the server can’t parse your current format.

check your file size first - telegram has limits and large images can cause 502s. also make sure you’re not reading the whole file into memory with fread(), that’s pretty inefficient. just pass the file handle directly in multipart like miat showed

Had this exact issue last month with Guzzle 5.x. It’s not just multipart formatting - Guzzle 5 handles requests differently than newer versions. With 5.3.0, you need explicit headers. Your server might reject the request because it can’t identify the content type boundary.

Try adding explicit headers to your multipart request. Check for timeout issues on larger files too. Some hosting environments have stricter multipart upload limits that trigger 502 errors even when formatting’s correct.

Also check your php.ini settings - upload_max_filesize and post_max_size. Sometimes the 502 comes from web server level before it hits your PHP code.

This topic was automatically closed 4 days after the last reply. New replies are no longer allowed.