欢迎您来到,李雷博客 | PHP博客        登录  |  注册

PHP下载远程图片到本地的函数代码

更新:2023-01-05 10:50:12
人气:417
来源:本站整理
A+

本篇文章给大家介绍PHP相关知识,主要内容是教大家怎么使用php下载采集的图片到本地并保存,希望对需要的朋友有所帮助!

PHP下载远程图片到本地的函数代码:

function down_remote_img($url='', $dirName='.', $fileName=''){
    if(empty($url)) return ['code'=>1,'msg'=>'地址不能为空'];
    $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);
    $file = 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($file);
    }

    $img_content = $imgBase64Code;//图片内容

    //echo $img_content;exit;
    if (preg_match('/^(data:\s*image\/(\w+);base64,)/', $img_content, $result)) {
        $fileType = $result[2];//得到图片类型png?jpg?gif?


        $fileName = $fileName == '' ? time() . rand(0, 9) . '.' . $fileType : $fileName. '.' . $fileType;
        $dirName = $dirName == '' ? './uploads/temp/' . date('Ym', time()) : $dirName;

        if (!file_exists($dirName)) {
            mkdir($dirName, 0777, true);
        }

        $res = @fopen ( $dirName . '/' . $fileName, "a" );
        fwrite($res, $file);
        fclose($res);

        return ['code'=>0,'msg'=>'sucess','path'=>$dirName . '/' . $fileName,'filename'=>$fileName];
    }

    return ['code'=>1,'msg'=>'下载失败'];
}
推荐的文章
# 发表我的评论
  /     /  
# 最近评论
暂时还没有评论,要不要说点什么?
  Ads by Google
  联系博主
Hello,本博客系统采用PHP和MySql开发,程序开发完全是因为个人爱好,是自己纯手写PHP源代码,未采用任何PHP框架!
QQ:858353007   微信号:lileihot123
网站地图
会员服务
关于我们
QQ:858353007
 
广告服务
加我微信
移动端访问
 
 
Copyright © 2014- 2024 www.mdaima.com All Rights Reserved.
李雷博客,专注PHP经验、PHP教程及PHP源代码开源下载分享的PHP博客!   ICP备案号:京ICP备10202169号-4