Thinkphp6 远程图片下载

星陨丶作者头像
星陨丶 2025-05-07

1、安装 GuzzleHttp ,如果已安装则可以忽略

composer require guzzlehttp/guzzle

2、完整代码

<?php
/**
 * 远程抓取下载文件
 * User: Holyrisk
 * Date: 2025/5/7
 * Time: 16:05
 */

namespace Holyrisk\download;


use GuzzleHttp\Client;

class DownloadHandle
{

    /**
     * @param $url 远程 URL
     * @param $file_path 保存的文件路径
     * @param $error_msg $msg 读取远程失败错误语
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function request($url,$file_path,$error_msg = '请求远程读取失败')
    {
        try{
            $http = new Client([
                'verify' => false,//绕过HTTPS证书校验
                'headers' => [
                    'Content-type' => 'application/json',
                ]
            ]);
            $repsone = $http->get($url);
            $data = $repsone->getBody()->getContents();

            if ($data !== false){
                self::mkdirFile($file_path);
                file_put_contents($file_path,$data);
            }else{
                throw new \Exception($error_msg);
            }
        }catch (\Exception $exception){
            $msg = '下载失败:'.$exception->getMessage();
            throw new \Exception($msg);
        }
    }

    /**
     * 图片
     * @param $url 远程 图片 URL
     * @param $file_path 保存的文件路径
     * @return string
     * @throws \GuzzleHttp\Exception\GuzzleException
     */
    public static function img($url,$file_path)
    {
        try{
            self::request($url,$file_path);
            //返回响应的 下载路径
            $root =  app()->getRootPath().'public';
            $return_path = ltrim($file_path,$root);
        }catch (\Exception $exception){
            throw new \Exception($exception->getMessage());
        }
        return $return_path;
    }


    /**
     * 根据文件路径 创建 目录文件夹
     * @param $file
     * @param int $mode
     * @return bool
     */
    public static function mkdirFile($file,$mode = 0755)
    {
        $rsp = true;
        $file_info = pathinfo($file);//dirname
        if (is_dir($file_info['dirname']) == false){
            $rsp = mkdir($file_info['dirname'],$mode,true);
        }
        return $rsp;
    }


}

3、测试

$url = 'http://gips0.baidu.com/it/u=1690853528,2506870245&fm=3028&app=3028&f=JPEG&fmt=auto?w=1024&h=1024';
//$url = 'https://www.trom.cn/UpFiles/Article/2025-03/20253118198999674.jpg';


$root =  app()->getRootPath().'public';
$path =  '/storage/test/'.date("Ymd",time());

//获取文件后缀
$extension = isset(pathinfo($url)['extension']) ? pathinfo($url)['extension'] : 'png';
//文件名称带后缀
$filename = uniqid().'.'.$extension;

//保存文件路径
$file_path = $root.$path.'/'.$filename;

$rsp = DownloadHandle::img($url,$file_path);
var_dump($rsp);

测试通过OK