<?php $headimg = "http://thirdwx.qlogo.cn/mmopen/vi_32/CW96JibTBRccMbXlDhTm6bGbO7eXAwIqCP0UiaQukLnfyFaVs9PVM9gLS8libx2GuH2kz6bNfp2GZQccYKKFr5BCA/132"; /* PHP远程下载微信头像存到本地,本地图片转base64 * $url 微信头像链接 * $path 要保存图片的目录 * $userid 用户唯一标识(用这个作为图片文件名,可以节省图片空间) */ function download_remote_pic($url,$path,$userid){ $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); $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 //相对路径 $relative_path=$path."/"; //绝对路径($_SERVER['DOCUMENT_ROOT']为网站根目录) $absolute_path = $_SERVER['DOCUMENT_ROOT'].$relative_path; if(!file_exists($absolute_path)){ //检查是否有该文件夹,如果没有就创建,并给予最高权限 mkdir($absolute_path,7777); } //文件名 $filename=$userid.".{$type}"; $new_file = $absolute_path.$filename; if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img_content)))) { var_dump(222); return $relative_path.$filename; }else{ var_dump(444); return false; } }else{ var_dump(111); return false; } } //测试一下 $userid = 'img'; $file = $_SERVER['DOCUMENT_ROOT']."/upload/headimg/".$userid.".jpeg"; //判断头像是否存在,不存在就下载 if(!file_exists($file)){ echo download_remote_pic($headimg,"/upload/headimg",$userid); }
标签:微信,图片链接,php,保存,本地 From: https://www.cnblogs.com/lyzaidxh/p/18056219