(就这么个小事,有多少公司多少项目没做到!!)
微信公众号项目,后端获取到授权用户的微信头像后,要自行下载保存,不下载的话,微信返回的头像链接会在一段时间后过期,无法访问!
下面是我写的两个简单实用方法:
1、文件下载,用于下载微信头像!
/**
* 下载文件并保存到指定目录
* @param $url
* @param $saveName
* @param string $savePath
* @return bool|int
*/
function downloadFileAndSave($url, $saveName, $savePath = 'images/') {
if (!file_exists($savePath)){
mkdir($savePath, 0777, true);
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 30);
$file = curl_exec($ch);
curl_close($ch);
$resource = fopen($savePath . $saveName, 'w');
$result = fwrite($resource, $file);
fclose($reso