在做微信上传素材文件时出了点问题,服务器提示media缺失,原上传代码如下:
function https_request($url,array $data = null) {
$curl = curl_init();
curl_setopt($curl, CURLOPT_URL, $url);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, FALSE);
if ($data){
curl_setopt($curl, CURLOPT_POST, 1);
curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
}
curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($curl);
curl_close($curl);
return $output;
}
将上传文件声明为
$data['media'] = @.'file.path';
于是就得到了上诉的错误。
在网上找了一堆资料之后,有人的建议是在设置fields之前关闭安全上传操作,代码如下
curl_setopt ( $curl, CURLOPT_SAFE_UPLOAD, false);
但是到运行时会出现以下错误:curl_setopt(): Disabling safe uploads is no longer supported
意思时该设置项已经不被支持。
之后在官方文档上找到:
CURLOPT_SAFE_UPLOAD | TRUE to disable support for the @ prefix for uploading files inCURLOPT_POSTFIELDS , which means that values starting with @can be safely passed as fields. CURLFile may be used for uploads instead. |
具体代码如下:
function postFile($url,$path,$others=null){
$ch = curl_init($url);
$cfile = new \CURLFile($path);
$others or $others = [];
$others['media'] = $cfile;
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_POST,1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $others);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
$output = curl_exec($ch);
curl_close($ch);
return $output;
}
最终成功将文件上传至服务器