PHP curl 上传文件版本兼容问题


做微信开发调用微信接口上传文件时,老是返回
{"errcode":41005,"errmsg":"media data missing hint: [mQbr_a0173ure1]"}
上传文件不存在。
搞了半天,最后是PHP版本不兼容问题
上传代码


$data = array('media' => '@' . $img);
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, 'POST');
curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, FALSE);
curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, FALSE);
curl_setopt($ch, CURLOPT_USERAGENT, 'Mozilla/5.0 (compatible; MSIE 5.01; Windows NT 5.0)');
curl_setopt($ch, CURLOPT_FOLLOWLOCATION, 1);
curl_setopt($ch, CURLOPT_AUTOREFERER, 1);
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
$info = curl_exec($ch);
curl_close($ch);




此代码在php5.6以前的版本都可以正常上传,但是PHP 5.6抛弃了@语法,只支持 CURLFile 方法上传。这种
语言设计不向后兼容我也是醉了。
5.6上传这样写
$data = array('media' => new CURLFile(realpath($tmp_name)));




另外也可以自己设计兼容方法:
if(version_compare(phpversion(),'5.5.0') >= 0 && class_exists('CURLFile')){
    $data['file'] = new CURLFile(realpath($tmp_name));
}else{
    $data['file'] = '@'.$tmp_name;
}




另外的另外,还可以配置一个CURL参数来解决这个问题:
curl_setopt( $ch, CURLOPT_SAFE_UPLOAD, false);
这句要放到
curl_setopt($ch, CURLOPT_POSTFIELDS, $data);之前
该设置官方说明
TRUE to disable support for the @ prefix for uploading files in CURLOPT_POSTFIELDS, 
which means that values starting with @ can be safely passed as fields. CURLFile may be used for uploads instead.
Added in PHP 5.5.0 with FALSE as the default value. PHP 5.6.0 changes the default value to TRUE.


大致意思设置为true时禁止@语法在CURLOPT_POSTFIELDS上传文件,使用CURLFile最为替代进行文件上传。
5.5版本增加该参数,PHP5.5默认是false,PHP5.6修改该默认值为true
官方参考
http://cn2.php.net/manual/en/function.curl-setopt.php

你可能感兴趣的:(PHP curl 上传文件版本兼容问题)