Peregrine
Peregrine

Reputation: 33

Telegram request "fopen failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request"

I am trying to send messages to my telegram bot. Exactly name variable can't allow me to do it.

    $arr = array(
      $phoneFieldset => $phone,
      $nameFieldset => $name,
      $messageFieldset => $message,
    );
    foreach($arr as $key => $value) {
      $txt .= "<b>".$key."</b> ".$value."%0A";
    };
    
    $request = "https://api.telegram.org/bot{$token}/sendMessage?chat_id={$chat_id}&parse_mode=html&text={$txt}";
    
    echo $request;
    
    $sendToTelegram = fopen($request,"r");

The request echo output, when the script fails:

https://api.telegram.org/botMYTOKEN/sendMessage?chat_id=-449128489&parse_mode=html&text=Телефон: 123%0AИмя: de%0AСообщение: 123213%0A

Warning: fopen(https://api.telegram.org/botMYTOKEN/sendMessage?chat_id=-449128489&parse_mode=html&text=Телефон: 123%0AИмя: de%0AСообщение: 123213%0A): failed to open stream: HTTP request failed! HTTP/1.1 400 Bad Request in C:\nginx\html\scripts\php\send-message-to-telegram.php on line 61 Ошибка. Сообщение не отправлено!

Line 61 is the one containing the fopen().

The request echo output, when the script works:

https://api.telegram.org/botMYTOKEN/sendMessage?chat_id=-449128489&parse_mode=html&text=Телефон: 123123%0AСообщение: 1213123%0A

Upvotes: 2

Views: 3206

Answers (1)

wowkin2
wowkin2

Reputation: 6355

The main problem here is that you need to encode Cyrillic characters to URL entities. You can do that using rawurlencode($txt). See full code below:

    $arr = array(
      $phoneFieldset => $phone,
      $nameFieldset => $name,
      $messageFieldset => $message,
    );
    foreach($arr as $key => $value) {
      $txt .= "<b>".$key."</b> ".$value."%0A";
    };

    $txt = rawurlencode($txt)  // To encode cyrillic entities

    $request = "https://api.telegram.org/bot{$token}/sendMessage?chat_id={$chat_id}&parse_mode=html&text={$txt}";
    
    echo $request;
    
    $sendToTelegram = fopen($request,"r");

P.S. Taken from @ed-lucas comment for others who will search for answer.

Upvotes: 1

Related Questions