微信图片下载并更换为本地ftp路径

说明
久了自己写的代码也不熟。
后台富文本中添加微信公众号内容时,对内容的图片进行抓取存到ftp上并生成url存在数据库中

/**
 * 富文本编辑器生成的html内容替换
 * @param $str    html微信
 * @return mixed  html替换完的
 */
function ftp_wx_img_down_up($str)
{
    //设置运行时间
    set_time_limit(300);
    //字符转义
    $str = htmlspecialchars_decode($str);
    //匹配图片
    $patter = "/<[img|IMG].*?src=[\'|\"](.*?(jpg|JPG|jpeg|JPEG|gif|GIF|png|PNG|bmp|BMP))[\'|\"].*?[\/]?>/i";
    //下载列表
    $downList = [];
    $ftpArr = [];
    //保存路径
    $path = "Public/upload/" . date("Ymd") . "/";
    //domain
    $host = C('FTP_SEVER') . DIRECTORY_SEPARATOR;
    //下载替换后的内容
    $retStr = preg_replace_callback($patter, function ($match) use (&$downList, &$ftpArr, $path, $host) {
        $temp['path'] = $path;
        $temp['count'] = 0;
        if (strpos($match[1], 'http') !== false) {
            $temp['url'] = $match[1];
            $temp['name'] = time() . rand(0, 1000000) . '.' . $match[2];
            $downList[] = $temp;
        } else {
            $temp['url'] = substr($match[1], 1);
            $temp['name'] = pathinfo($match[1], PATHINFO_BASENAME);
            $ftpArr[] = $temp;
        }
        return "<img src='" . $host . $path . $temp['name'] . "' width='100%'>";
    }, $str);

    $count = 1;
    $startTime = time();
    queue:
    $temp = array_shift($downList);
    if ((time() - $startTime < 300) && ($temp['count'] < 3)) {
        $res = downPic($temp['url'], $temp['name'], $temp['path'], 5 * $count);
        if (!$res) {
            $temp['count']++;
            array_push($downList, $temp);
        } else {
            array_push($ftpArr, $res);
        }
    }
    if (!empty($downList)) {
        goto queue;
    }

    foreach ($ftpArr as $key => $val) {
        $furl = C('REMOTE_ROOT') . $val['path'] . $val['name'];
        ftp_upload($furl, $val['url']);
    }

    return $retStr;
}

/**
 * PHP下载远程图片
 * @param string $url      图片路径URL
 * @param string $savePath 图片本地保存路径
 * @param string $filename 保存名称,不带后缀
 * @return array
 */
function downPic($url, $filename, $savePath = '', $timeout = 30)
{
    $url = str_replace(" ", "%20", $url);
    // 没有图片路径或保存路径为空
    if (empty($url) || empty($savePath)) return false;
    // 远程图片不存在
    if (!@fopen($url, 'r')) return false;
    $ext = strrchr($filename, ".");
    $data = getimagesize($url);
    // 根据文件Mime类型判断
    if (!in_array($data['mime'], array('image/gif', 'image/jpeg', 'image/png', 'image/jpg'))) return false;
    // 也可根据后缀来判断
    if ($ext != '.gif' && $ext != '.jpg' && $ext != '.png' && $ext != '.jpeg') return false;

    if (!file_exists($savePath)) {
        mkdir($savePath, 0777, true);
    }
    //两种下载方式
    if (function_exists('curl_init')) {
        $https = true;
        if (strpos($url, 'https') === false) {
            $https = false;
        }
        $file = request($url, $https);
    } else {
        ob_start();
        readfile($url);
        $file = ob_get_contents();
        ob_end_clean();
    }
    file_put_contents($savePath . $filename, $file);

    $size = filesize($savePath . $filename);
    if ($size) {
        return [
            'url'  => $savePath . $filename,
            'path' => $savePath,
            'name' => $filename
        ];
    } else {
        unlink($savePath . $filename);
        return false;
    }
}

//可以发送https,http,get方式,post方式  post数据发送
function request($url, $https = true, $method = 'get', $data = null)
{
    //1.初始化curl
    $ch = curl_init($url);
    //2.设置相关的参数
    //字符串不直接输出,进行一个变量的存储
    curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
    // curl_setopt($ch, CURLOPT_HEADER, 1);
    //判断是否为https请求
    if ($https === true) {
        //为了确保https请求能够请求成功
        curl_setopt($ch, CURLOPT_SSL_VERIFYPEER, false);
        curl_setopt($ch, CURLOPT_SSL_VERIFYHOST, false);
    }
    //判断是否为post请求
    if ($method == 'post') {
        curl_setopt($ch, CURLOPT_POST, true);
        curl_setopt($ch, CURLOPT_POSTFIELDS, $data);
    }
    //3.发送请求
    $str = curl_exec($ch);
    //4.关闭连接
    curl_close($ch);
    //返回请求到的结果
    return $str;
}

posted on 2019-10-25 13:59  何苦->  阅读(507)  评论(0编辑  收藏  举报

导航