php使用Curl下载微信头像
文章描述:
php使用curl下载远程图片
远程图片地址
$headimg = "https://wx.qlogo.cn/mmhead/UsichrXlnR9JQXG7s95vd1yGRwbGFuibSMWPzyWuzurDXM4tpdAECYZQ/0";
cur下载方法
/* PHP远程下载微信头像存到本地,本地图片转base64
* $url 微信头像链接
* $path 要保存图片的目录
* $userid 用户唯一标识(用这个作为图片文件名,可以节省图片空间)
*/
function download_remote_pic($url,$path,$userid) {
$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',
);
$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;
//echo $absolute_path;exit;
if(!file_exists($absolute_path)) {
//检查是否有该文件夹,如果没有就创建,并给予最高权限
mkdir($absolute_path, 0700);
}
//文件名
$filename=$userid.".{$type}";
$new_file = $absolute_path.$filename;
if (file_put_contents($new_file, base64_decode(str_replace($result[1], '', $img_content)))) {
return $relative_path.$filename;
} else {
return false;
}
} else {
return false;
}
}
使用
$id = 'curl-download-img';
//测试一下
$file = $_SERVER['DOCUMENT_ROOT']."/upload/".$id.".jpeg";
//判断头像是否存在,不存在就下载
if(!file_exists($file)) {
download_remote_pic($headimg,"/upload",$id);
}
发布时间:2021/07/08
发表评论