下载微信头像到本地

   通过微信接口,可以获取到微信头像的链接,例如:http://thirdwx.qlogo.cn/mmopen/y5vdnz5cVsANsZChfWe6IWsZ4PnWV9Tq78nvWoLvvvqWs0jOowJgAxSLZMqzibA41Fib82zZX6YGpd2D4jIfrN42XBXpmgZoFN,但是有时候我们需要下载微信的头像下来;

// 下载微信头像到本地
function upload_headimg($headimgurl){
    $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',);
     $url= $headimgurl;
     $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);
     $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;//图片内容
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img_content, $result)) {
         $type = $result[2];//得到图片类型png?jpg?gif? 
         $new_file = "./public/headimg/".date("YmdHis").".".$type; 
         if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img_content)))) {
            return upload_img($new_file);
            // return "http://weixin.wy100.com/hyuser_sys/oldjie/".$new_file;
            // exit;
        }
    } 
    return false;
}

 

你可能感兴趣的:(php,微信)