php把服务器上的资源下载并保存本地

1.把服务器资源(图片)下载到本地

 <?php
  $time = md5(time());
                $arr = explode('.', $imgRow['img_path']);
                $ext = end($arr);
                $localImgPath = storage_path('app/public/' . $time . '_' . $ext);
                $downloadFlag = $this->getImg($imgRow['img_path'], $localImgPath);


   //下载图片
    private function getImg($url = "", $filename = "")
    {
        //去除URL连接上面可能的引号
        //$url = preg_replace( '/(?:^['"]+|['"/]+$)/', '', $url );
        $hander = curl_init();
        $fp = fopen($filename, 'wb');
        curl_setopt($hander, CURLOPT_URL, $url);
        curl_setopt($hander, CURLOPT_FILE, $fp);
        curl_setopt($hander, CURLOPT_HEADER, 0);
        curl_setopt($hander, CURLOPT_FOLLOWLOCATION, 1);
        //curl_setopt($hander,CURLOPT_RETURNTRANSFER,false);//以数据流的方式返回数据,当为false是直接显示出来
        curl_setopt($hander, CURLOPT_TIMEOUT, 60);
        curl_exec($hander);
        curl_close($hander);
        fclose($fp);
        return true;
    }

2,把本地资源上传到服务器

 <?
  //上传到图片到 阿里云OSS
                    $savename = Storage::putFile('uploads', $localImgPath);
                    $ossBaseUrl = env('OSS_URL');
                    $ossImg = $ossBaseUrl . '/' . $savename;
                    $data[] = $ossImg;
                    unlink($localImgPath);

use Illuminate\Http\File;
use Illuminate\Support\Facades\Storage;

// 自动计算文件名的MD5值...
Storage::putFile('photos', new File('/path/to/photo'));

// 手动指定文件名...
Storage::putFileAs('photos', new File('/path/to/photo'), 'photo.jpg');

 

posted on 2021-05-13 14:16  kevin_yang123  阅读(462)  评论(0编辑  收藏  举报