关于微信三方登录后,头像处理问题

时间:2024-02-24 13:02:15

首先说一下遇到的情况:在进行微信三方登录后,需要拿到用户的头像,并保存到服务器和进行相关的裁剪。微信返回用户信息中有headimgurl对应的头像地址,浏览器可直接打开该地址,若用file_get_contents($url),函数进行操作,会显示图片损坏,无法打开.

解决方法:1.

 

1 $file_contents = file_get_contents($url);
2 $h = fopen(\'download/\'.$uid.\'.jpg\', \'a\');
3 fwrite($h, $file_contents);
4 fclose($h);

 

2.

 1 $ch = curl_init();
 2             $timeout = 5;
 3             curl_setopt ($ch, CURLOPT_URL, $url);
 4             curl_setopt ($ch, CURLOPT_RETURNTRANSFER, 1);
 5             curl_setopt ($ch, CURLOPT_CONNECTTIMEOUT, $timeout);
 6             $file_contents = curl_exec($ch);
 7             curl_close($ch);
 8             $h = fopen(\'download/\'.$uid.\'.jpg\', \'a\');
 9             fwrite($h, $file_contents);
10             fclose($h);

比较:file_get_contens()函数打开外网资源会耗费过多的内存,并且在相应方面很慢,用第二种方法会比第一种快30%-40%;