环境
$ php -vPHP 7.1.23
依赖
composer require "guzzlehttp/guzzle=6.5"composer require "ramsey/uuid=3.9"
示例
require_once './vendor/autoload.php';use GuzzleHttp\Client;use Ramsey\Uuid\Uuid;function safeMakeDir($dir){ if (!file_exists($dir)) { mkdir($dir, 0777, true); }}function getRandomString(){ return Uuid::uuid4()->toString();}function getFileNameExtension($filename){ return array_slice(explode('.', $filename), -1)[0];}function getUrlContent($url){ $client = new Client(); $response = $client->get($url); $body = $response->getBody(); return $body->getContents();}function saveUrlToLocalFile($url, $dir){ safeMakeDir($dir); $ext = getFileNameExtension($url); $uuid = getRandomString(); $filename = "{$dir}/{$uuid}.{$ext}"; $content = getUrlContent($url); file_put_contents($filename, $content);}function main(){ $url = 'https://file.lsjlt.com/upload/f/202309/20/jvfz2fu5l0w.jpg&rf=LaDigue_1920x1080.jpg'; $dir = 'temp'; saveUrlToLocalFile($url, $dir);}main();
文件保存到了:
temp/113380ed-bf1b-40cf-8b19-5aefcb66fc17.jpg