首页 > 解决方案 > curl PHP中参数的URLENCODE如何工作?

问题描述

我有一个非常奇怪的问题,urlencode现在我解释一下:

我有一个电报机器人,可以通过 url 向我发送消息,因此我想添加urlencode我将粘贴到 url 中的 fot 文本。

但如果使用CURLOPT_POSTFIELDS我有一个奇怪的问题。


要发送的消息是:

  This is an example my friend

但是如果使用urlencode并且CURLOPT_POSTFIELDS输出是:

  This+is+an+example+my+friend

现在我展示完整的代码:

$notifica= urlencode("This is an example my friend");
sendMessage(xxx, $notifica);
sendMessage_2($notifica);


function sendMessage($chat_id, $message){           
   $params=[
    'chat_id' => $chat_id,
    'parse_mode' => 'HTML',
    'text' => $message
   ];

   $url= 'https://api.telegram.org/botxxx';
   $ch = curl_init($url);
   curl_setopt($ch, CURLOPT_HEADER, false);
   curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 3500);
   curl_setopt($ch, CURLOPT_TIMEOUT_MS, 3500);
   curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
   curl_setopt($ch, CURLOPT_POST, 1);
   curl_setopt($ch, CURLOPT_POSTFIELDS, $params);
   curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
   $result = curl_exec($ch);
   curl_close($ch); 
}

function sendMessage_2($mess){          
    $url= 'https://api.telegram.org/botxxx/sendMessage?chat_id=xxx&parse_mode=HTML&text='.$mess;

    $ch = curl_init();  
    curl_setopt($ch, CURLOPT_URL, $url);
    curl_setopt($ch, CURLOPT_HEADER, 0);
    curl_setopt($ch, CURLOPT_CONNECTTIMEOUT_MS, 3500);
    curl_setopt($ch, CURLOPT_TIMEOUT_MS, 3500);
    $result = curl_exec($ch);
    curl_close($ch);    
}

我希望有人可以帮助我......非常感谢,对不起我的英语

标签: phpcurltelegramtelegram-boturlencode

解决方案


urlencode()当您将参数放入带有CURLOPT_POSTFIELDS. 文档说:

如果value是数组,则Content-Type标头将设置为multipart/form-data

这种格式不需要 URL 编码,所以服务器不会自动解码。因此,编码中使用的字符(空格编码为+,其他使用的特殊字符%后跟十六进制代码)将按字面处理。


推荐阅读