我正在尝试构建一个电报机器人,但是麻烦是由于更新了PHP 5.6而导致的PHP函数更改。
下面是我发现的基本代码,可适应php 5.6中的更改。
#$filePhoto = curl_file_create($filepath, 'image/jpg', 'heInternet'); //**LINE 39**
$filePhoto = new CURLFile($filepath, 'image/jpg', 'heInternet'); //**LINE 40**
//$texto = $_POST['msg'];
$content = array(
'chat_id' => "@BugTheInternet",
'photo' => $filePhoto
);
//curl required to post
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_SAFE_UPLOAD, false); // required as of PHP 5.6.0
curl_setopt($ch, CURLOPT_POSTFIELDS, $filePhoto); //**LINE 53**
curl_setopt($ch, CURLOPT_HTTPHEADER, array('Content-Type: multipart/form-data'));
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false); //fix http://unitstep.net/blog/2009/05/05/using-curl-in-php-to-access-https-ssltls-protected-sites/
// receive server response ...
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$server_output = curl_exec ($ch);
这是我得到的错误:
不推荐使用:curl_setopt():文件的@filename API的用法不建议上传。请改用CURLFile类C:\ xampp某处\ somefile.php,第53行
[当我在第53行中将$ content更改为$ filePhoto时。它将运行,并且Telegram服务器以JSON发送消息。服务器回复:
"{"ok":false,"error_code":400,"description":"Error: Bad Request: there is no photo in request"}"
我已经在互联网上搜索了数小时,找到了解决方案。顺便说一句,我正在为PHP 5.6建议使用两种方式,它在第39行40中。
[如果您遇到此问题,请帮助我。谢谢。
您是否尝试过以这种方式发送它[[hardcore?
$ch = curl_init("https://api.telegram.org/bot<token>/sendPhoto&chat_id=<chatID>&photo=<path/to/your/image>");
curl_setopt($ch, CURLOPT_POST, 1);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, false);
curl_exec($ch);
curl_close ($ch);
首先,我在发送消息时也将东西用于cURL,但是对我来说不起作用。因此,我hardcored就像上面的示例一样,它才起作用。POSTFIELDS和其他correct
'chat_id' => "@BugTheInternet",
从$ content开始并添加chat_id来卷曲URL,因为PHP的cURL库消失,返回错误消息“创建失败formpost数据”,当尝试使用包含值的数组时从...开始 '@'。如果将数组更改为采用类似URL编码格式的字符串,则不会发生问题。参考:https://bugs.php.net/bug.php?id=50060
function json($url, array $fields) {
$ch = curl_init($url);
$ok = 1;
$ok &= curl_setopt($ch, CURLOPT_ENCODING, 'UTF-8');
$ok &= curl_setopt($ch, CURLOPT_FOLLOWLOCATION, true);
$ok &= curl_setopt($ch, CURLOPT_AUTOREFERER, true);
$ok &= curl_setopt($ch, CURLOPT_TIMEOUT, 120);
$ok &= curl_setopt($ch, CURLOPT_HTTPHEADER, [
"Accept: application/json"
]);
$ok &= curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$ok &= curl_setopt($ch, CURLOPT_POSTFIELDS, $fields);
$ok &= curl_setopt($ch, CURLOPT_HTTPHEADER, ["Content-Type:multipart/form-data"]);
if ($ok !== 1) {
user_error("curl_setopt failed");
}
$res = curl_exec($ch);
if ($res === false) {
var_dump($res);
user_error(curl_error($ch));
}
$code = curl_getinfo($ch, CURLINFO_HTTP_CODE);
curl_close($ch);
if ($res === false) {
user_error('curl_exec fail');
}
$json = json_decode($res, true);
if (! is_array($json)) {
print_r($res);
user_error("http_json::failed decoding");
}
return $json;
}
$f = new \CurlFile("/path/to/file.jpg", 'image/jpeg', 'filename.jpg');
$args = [
"photo" => $f,
"chat_id" => $group,
"caption" => "Hello world"
];
$url = "https://api.telegram.org/bot$token/sendPhoto";
var_dump( json($url, $args) );
这是在PHP7上,技巧似乎是两件事: