PHP curl 上传文件版本兼容问题
2016-01-26 20:36
751 查看
做微信开发调用微信接口上传文件时,老是返回
{"errcode":41005,"errmsg":"media data missing hint: [mQbr_a0173ure1]"}
上传文件不存在。
搞了半天,最后是PHP版本不兼容问题
上传代码
此代码在php5.6以前的版本都可以正常上传,但是PHP 5.6抛弃了@语法,只支持 CURLFile 方法上传。这种
语言设计不向后兼容我也是醉了。
5.6上传这样写
另外也可以自己设计兼容方法:
另外的另外,还可以配置一个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
{"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命名空间 namespace 和 自动加载
- THINKPHP钩子方法
- phpstorm配置自动上传代码
- Ubuntu 14.04 FTP服务器--vsftpd的安装和配置
- MR-2.输出格式(OutputFormat)Multiple outputs多目录输出
- PHPExcel如何把该列的值设置为文本无科学计数?
- 学习Slim Framework for PHP v3 (三)
- php开启com组件注意事项
- LAMP之二(PHP-FPM)
- PHP学习(1)——我为什么要学PHP
- PHP学习(1)——我为什么要学PHP
- PHP 安装
- PHP编程入门的基本语法知识点总结
- php 无法载入 mysql 扩展 的完美解决方案
- 在dos下使用简单的ftp命令
- PHP设计模式
- phpstorm+xdebug作用解释及原理分析
- heredoc和nowdoc的区别
- phpdoc 使用(一)
- php 创建验证码方法