最近做一个有关微信授权登录的项目,关于授权就不多说了,我获取到用户基本信息,格式如下:
$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);
}
}
}
}
哈哈,我是一个专注接口的小菜鸟,多多指教!
**粗体** _斜体_ [链接](http://example.com) `代码` - 列表 > 引用
。你还可以使用@
来通知其他用户。