本文主要和大家分享微信授權後用戶頭像保存到伺服器實現方法,最近做一個有關微信授權登錄的項目,關於授權就不多說了,我獲取到用戶基本信息,格式如下:
$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']); } //快来写你的注册或者修改代码吧! }
儲存圖片
rrreee指定位置建立檔案
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; }
希望對大家有用。
相關推薦:
以上是微信授權後使用者頭像儲存到伺服器實作方法的詳細內容。更多資訊請關注PHP中文網其他相關文章!