默认微信头像是一个URL地址,保存在微信的服务器上,如果授权登录后换了头像获取的头像地址就会失效,图片显示不出来体验就会比较差。解决办法就是在登录的时候把微信头像保存到本地服务器,这样就不存在这样的情况,用户发现头像没更新可以手动点击更新或者程序自动判断更新。
下面是PHP中如果把用户的微信头像保存到本地服务器,形成永久的头像。
function download_remote_pic($url)
{
$header = [
'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, $url);
curl_setopt($curl, CURLOPT_RETURNTRANSFER, true);
curl_setopt($curl, CURLOPT_FOLLOWLOCATION, true);
curl_setopt($curl, CURLOPT_ENCODING, 'gzip');
curl_setopt($curl, CURLOPT_HTTPHEADER, $header);
curl_setopt($curl, CURLOPT_SSL_VERIFYPEER, false); // 跳过证书检查
curl_setopt($curl, CURLOPT_SSL_VERIFYHOST, true); // 从证书中检查SSL加密算法是否存在
$data = curl_exec($curl);
$code = curl_getinfo($curl, CURLINFO_HTTP_CODE);
curl_close($curl);
if ($code == 200) {
//把URL格式的图片转成base64_encode格式的!
$imgBase64Code = "data:image/jpeg;base64," . base64_encode($data);
}
$img_content = $imgBase64Code; //图片内容
//echo $img_content;exit;
if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img_content, $result)) {
var_dump($result);
$type = $result[2]; //得到图片类型png?jpg?gif?
$new_file = "./openid" . ".{$type}";
if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img_content)))) {
return $new_file;
}
}
}
$new_file = download_remote_pic('https://wx.qlogo.cn/mmopen/vi_32/20JUJpvD2IO8TyKTuLTu8o2IXlXobcA8OLxsZ2OBTLAEG9rrMXGicJnCicqdz6vSP2sYpMrFHsZ9FnUCAev3taAA/132');
echo $new_file;
保存到本地的图片用OPENID命名防止冲突,调用的时候只要有用户的OPENID就可以随时调用。