PHP 5.6 微信上传临时素材的坑


/*
* * 上传素材 */ function add_material($url){ $access_token = wx_access_token(); $wx_url = "https://api.weixin.qq.com/cgi-bin/material/add_material?access_token={$access_token}&type=image" $real_path = "{$_SERVER['DOCUMENT_ROOT']}{$url}"; $result = http_post($wx_url, $real_path); $arr = json_decode($result,true); return $arr; } /** * 获取access_token */ function wx_access_token(){ $config=C('WEIXINPAY_CONFIG'); $url = 'https://api.weixin.qq.com/cgi-bin/token?grant_type=client_credential&appid='.$config['APPID'].'&secret='.$config['APPSECRET']; $result = json_decode(wx_curl($url),true); return $result['access_token']; }
function http_post($url ='' , $fileurl = '' )
{
    $curl = curl_init();
    if(class_exists('\CURLFile')){
        curl_setopt ( $curl, CURLOPT_SAFE_UPLOAD, true); 
        $data = array('media' => new \CURLFile($fileurl));
    }else{
        if (defined ( 'CURLOPT_SAFE_UPLOAD' )) {  
            curl_setopt ( $curl, CURLOPT_SAFE_UPLOAD, false );  
        }  
        $data = array('media' => '@' . realpath($fileurl));
    }
    curl_setopt($curl, CURLOPT_URL, $url);
    curl_setopt($curl, CURLOPT_POST, 1);
    curl_setopt($curl, CURLOPT_POSTFIELDS, $data);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, 1);
    curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); 
    $output = curl_exec($curl);
    curl_close($curl);
    return $output;
}

以上是我的完整代码。

先说说我的环境吧,phg5.6+apache2.4

  1. 图片上传一定要用本地的绝对路径 例 curl -F media=@C:/Users/Administrator/Desktop/phpStudy/WWW/项目名称/Upload/qrcode/2017-10-08/657d112ce5b2e4c02699faa4b369c6ee.png
  2. 微信access_token使用时长7200秒 (我这里偷懒没有设置,不过你们要注意哦)
  3. PHP版本问题 5.6和5.6以上的版本 在curl内要设置 
    curl_setopt ( $curl, CURLOPT_SAFE_UPLOAD, true); 
    $data = array('media' => new \CURLFile($fileurl));
  4. PHP5.5及以下版本
    if (defined ( 'CURLOPT_SAFE_UPLOAD' )) {  
          curl_setopt ( $curl, CURLOPT_SAFE_UPLOAD, false );  
    }  
    $data = array('media' => '@' . realpath($fileurl));
  5. CURLOPT_SSL_VERIFYPEER:是否检测服务器的证书是否由正规浏览器认证过的授权CA颁发的。
     
  

 

posted @ 2017-10-08 10:52  GreenForestQuan  阅读(2043)  评论(0编辑  收藏  举报