PHP CURL 多部分表单数据无法上传文件(PHP Ver. 5.6)
PHP CURL multipart form data not uploading file (PHP Ver. 5.6)
我有一个向 Telegram 发送请求的方法,这个功能在我的服务器上正常运行。传输到客户服务器后,我从 Telegram 收到错误消息:Bad Request: URL host is empty
。
通过 Curl 发送的数据是:
$data = array(
"chat_id" => "user_id",
"video" => "@/path/to/file/tested/successfully",
"caption" => "My Text"
);
curl设置的选项如下:
curl_setopt($ch, CURLOPT_URL, 'URL/TO/TELEGRAM/API');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
这段代码在我的服务器上工作正常,我认为必须在服务器上设置一个配置。
另一个应该相关的问题是:当我提供错误的文件路径时,在第一台服务器上我从 curl 得到预期的 Error Code: 3, Couldn't open file
但在第二台服务器上我会再次得到 Bad Request: URL host is empty
。
所以也许我可以说第二台服务器上的 curl 无法理解 video
索引是一个文件。
第一台服务器是专用的,但第二台是共享主机(已测试 2 台主机) (发现 1)
第一台服务器 php 版本是 5.5.38,但第二台是 5.6 (发现 2)
将第二个 php 版本更改为 5.5.38 后,它可以正常工作 (发现 3)
任何帮助将不胜感激
在 php ver 5.5 及更高版本中设置 curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true)
并将 @/pathToFile
更改为 new \CURLFile($pathToFile)
。
根据 php changeLog :
Uploads using the @file syntax are now only supported if the CURLOPT_SAFE_UPLOAD option is set to FALSE. CURLFile should be used instead.
将 CURLOPT_SAFE_UPLOAD 设为 false 不是最佳做法,已弃用
阅读第一条评论 here 了解有关 CURLFile 的更多信息。
我有一个向 Telegram 发送请求的方法,这个功能在我的服务器上正常运行。传输到客户服务器后,我从 Telegram 收到错误消息:Bad Request: URL host is empty
。
通过 Curl 发送的数据是:
$data = array(
"chat_id" => "user_id",
"video" => "@/path/to/file/tested/successfully",
"caption" => "My Text"
);
curl设置的选项如下:
curl_setopt($ch, CURLOPT_URL, 'URL/TO/TELEGRAM/API');
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 0);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, array("Content-type: multipart/form-data"));
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "POST");
curl_setopt($ch, CURLOPT_POST, TRUE);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
这段代码在我的服务器上工作正常,我认为必须在服务器上设置一个配置。
另一个应该相关的问题是:当我提供错误的文件路径时,在第一台服务器上我从 curl 得到预期的 Error Code: 3, Couldn't open file
但在第二台服务器上我会再次得到 Bad Request: URL host is empty
。
所以也许我可以说第二台服务器上的 curl 无法理解 video
索引是一个文件。
第一台服务器是专用的,但第二台是共享主机(已测试 2 台主机) (发现 1)
第一台服务器 php 版本是 5.5.38,但第二台是 5.6 (发现 2)
将第二个 php 版本更改为 5.5.38 后,它可以正常工作 (发现 3)
任何帮助将不胜感激
在 php ver 5.5 及更高版本中设置 curl_setopt($ch, CURLOPT_SAFE_UPLOAD, true)
并将 @/pathToFile
更改为 new \CURLFile($pathToFile)
。
根据 php changeLog :
Uploads using the @file syntax are now only supported if the CURLOPT_SAFE_UPLOAD option is set to FALSE. CURLFile should be used instead.
将 CURLOPT_SAFE_UPLOAD 设为 false 不是最佳做法,已弃用
阅读第一条评论 here 了解有关 CURLFile 的更多信息。