PHP7 cURL上传文件

在做微信上传素材文件时出了点问题,服务器提示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_UPLOADTRUE 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.
于是尝试使用CURLFile(PHP5.5以上开始支持),

具体代码如下:

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;
    }
最终成功将文件上传至服务器

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值