微信授權後獲取使用者頭像儲存到伺服器

nice花椒發表於2019-02-16

最近做一個有關微信授權登入的專案,關於授權就不多說了,我獲取到使用者基本資訊,格式如下:

$user_info = `{"openid":"xx","nickname":"nice花椒.","sex":2,"language":"zh_CN","city":"杭州","province":"浙江","country":"中國","headimgurl":"http://wx.qlogo.cn/mmopen/vi_32/Q0j4TwGTfTJPpziaqOoIpGia9ZVj9fheAwLmTiavV4rxR40NQ1zPQPyiaMY58FEISDIfpn0q5VeeXliaKyiaiabgK2ZHg/0","privilege":[]}`;

直接把headimgurl入庫儲存,bug來了。

話不多說,進入正題:

微信返回的是json格式

$user_arr = json_decode($user_info, true);

獲取使用者openid對比資料庫,判斷是不是首次授權

$mem_info= $member->getuserinfo(array(`openid`=>$user_arr[`openid`]));

首次授權或者頭像連結地址與上次不同

if(!$mem_info || $mem_info[`wximage`]!=$user_info[`headimg`]){
    $headimgurl = saveheadimgurl($user_arr[`headimgurl`]);
    $headimg ? 0 : $headimg=`lib/avata.jpg` ;
    if($mem_info[`wximage`]!=$user_info[`headimg`]){
        unlink($mem_info[`headimg`]);
    }
    //快來寫你的註冊或者修改程式碼吧!
}

儲存圖片

function saveheadimgurl($headimg){
    $header = array(
         `User-Agent: Mozilla/5.0 (Windows NT 6.1; Win64; x64; rv:45.0) Gecko/20100101 Firefox/45.0`,      
         `Accept-Language: zh-CN,zh;q=0.8,en-US;q=0.5,en;q=0.3`,      
         `Accept-Encoding: gzip, deflate`,
    );
    $curl = curl_init();
    curl_setopt($curl, CURLOPT_URL, $headimg);
    curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);  
    curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
    curl_setopt($curl, CURLOPT_HTTPHEADER,$header);
    $dataimg = curl_exec($curl);
    $code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
    curl_close($curl);  
    if ($code == 200) {     
        $imgBase64Code = "data:image/jpeg;base64," . base64_encode($dataimg);
    }  
    $img_content=$imgBase64Code;
    if (preg_match(`/^(data:s*image/(w+);base64,)/`, $img_content, $result)){   
         $type = $result[2];
         create(DOFILESPATH."head"); 
         $new_file = DOFILESPATH."head/".md5(uniqid(rand())).".{$type}"; 
         if (file_put_contents($new_file, base64_decode(str_replace($result[1],``, $img_content))))  
         {  
             return $new_file;
         }
     }
     return false;
}

指定位置建立檔案

function create($dir){
    if(is_dir($dir)){
        $temp = explode(`/`,$dir);
        $cur_dir = ``;
        for($i=0; $i<count($temp); $i++){
            $cur_dir .= $temp[$i].`/`;
            if(!is_dir($cur_dir)){
                @mkdir($cur_dir,777);
            }
        }
    }
}

哈哈,我是一個專注介面的小菜鳥,多多指教!

相關文章