PHP8.1.21版本已发布
vue8.1.21版本已发布
jquery8.1.21版本已发布

Laravel 5 怎么保存远程图片到本地?

不言
不言 原创
2018-05-15 11:26:34 5948浏览

Laravel的FileSystem是否支持这样做(尤其是copy等函数)?

file_get_contents的话,如果是HTTPS网站会遇到SSL验证失败的错误,但又不能忽略掉这个错误。

回复内容:

Laravel的FileSystem是否支持这样做(尤其是copy等函数)?
file_get_contents的话,如果是HTTPS网站会遇到SSL验证失败的错误,但又不能忽略掉这个错误。

用GuzzleHttp即可。
加上:

use GuzzleHttp\Client;
use GuzzleHttp\Exception\GuzzleException;
$client = new Client(['verify' => false]);  //忽略SSL错误
$response = $client->get($url, ['save_to' => public_path($file)]);  //保存远程url到文件

可以用try catch写。

GuzzleHttp获取远程资源。Storage处理文件存储。

try {
    $client = new \GuzzleHttp\Client();
    $data = $client->request('get','http://xxxx')->getBody()->getContents();
    Storage::disk('local')->put('filename', $data);
} catch (\GuzzleHttp\RequestException $e) {
    echo 'fetch fail';
}
SSL证书验证失败的问题是以为你本地没有最新的ca证书列表,下载一个就行了
$client = new \GuzzleHttp\Client($url,[
    'curl.options' => [
        CURLOPT_SSL_VERIFYPEER=>2,
        CURLOPT_SSL_VERIFYHOST=true,
    ]
]);

用curl可以搞定

file_put_contents('/tmp/logo.gif',file_get_contents('https://www.baidu.com/img/bdlogo.gif'));

只要你的PHP添加了OpenSSL支持(--with-openssl),那file_get_contents就肯定支持HTTPS的.
如果提示出错:
SSL operation failed with code 1. OpenSSL Error messages:
error:14090086:SSL routines:ssl3_get_server_certificate:certificate verify failed
那就下载cacert.pem文件,然后在php.ini指定,然后重启PHP服务就好:

wget https://curl.haxx.se/ca/cacert.pem
php.ini:
openssl.cafile=/path/to/cacert.pem

var_export(openssl_get_cert_locations());
array (
  'default_cert_file' => '/opt/phpdroid/deps/ssl/cert.pem',
  'default_cert_file_env' => 'SSL_CERT_FILE',
  'default_cert_dir' => '/opt/phpdroid/deps/ssl/certs',
  'default_cert_dir_env' => 'SSL_CERT_DIR',
  'default_private_dir' => '/opt/phpdroid/deps/ssl/private',
  'default_default_cert_area' => '/opt/phpdroid/deps/ssl',
  'ini_cafile' => '',
  'ini_capath' => '',
)
声明:本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系admin@php.cn核实处理。
上一条:Web登录Authorization验证 下一条:&currentDate