php集成minio

1.php-集成minio

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
1.通过访问minio的官网,我们得知官方已经提供了很多现有的sdk(针对多语言的sdk)来简化client端的交互体验,

但是官网没有对应的文档
不要慌,php有单独的客户端sdk,但是叫aws-sdk-php
(https://docs.min.io/docs/how-to-use-aws-sdk-for-php-with-minio-server.html)此地址,没有找到对应的html,但是真的有aws-sdk-php
https://docs.aws.amazon.com/zh_cn/sdk-for-php/v3/developer-guide/welcome.html
https://docs.aws.amazon.com/zh_cn/sdkref/latest/guide/overview.html

2.安装依赖(一定要阿里云): composer require aws/aws-sdk-php:3.319.2
如果直接安装composer require aws/aws-sdk-php,会安装最新版本,使用会报错,因为最新版只支持 PHP 8.1.x 以上
所以安装的时候要添加版本,3.319.2支持7.2.x的版本
The latest SDK versions require PHP 8.1.x, "aws/aws-sdk-php": "3.319.2" works with PHP 7.2.x!!! So what do I propose? If you don't want or can't upgrade to PHP 8, you can downgrade your SDK! In my example I use "aws/aws-sdk-php": "3.319.2", FULLY compatible with php": "^7.2.5 !!!

安装时可能报其他依赖版本不兼容的错:
Problem 1
- Root composer.json requires aws/aws-sdk-php 3.319.2 -> satisfiable by aws/aws-sdk-php[3.319.2].
- aws/aws-sdk-php 3.319.2 requires guzzlehttp/guzzle ^6.5.8 || ^7.4.5 -> found guzzlehttp/guzzle[6.5.8, 7.4.5, ..., 7.9.2] but the package is fixed to 6.5.5 (lock file version) by a partial update and that version does not mat
ch. Make sure you list it as an argument for the update command.
Problem 2
- topthink/think-captcha is locked to version v1.0.8 and an update of this package was not requested.
- topthink/think-captcha v1.0.8 requires topthink/think-installer >=1.0.10 -> satisfiable by topthink/think-installer[v1.0.12].
- topthink/think-installer v1.0.12 requires composer-plugin-api ^1.0 -> found composer-plugin-api[2.6.0] but it does not match the constraint.

解决(没成功):
composer require guzzlehttp/psr7:1.9.1
composer require guzzlehttp/guzzle:6.5.8

3.安装时如果还报错就更新依赖(能解决,但是会更新其他的依赖包,比如redis,导致 redis报错,目前只发现redis,其他的得看项目报错时才知道): composer update

4.安装成功后
1.会在vendor目录下找到aws目录
2. 在composer.json文件里找到
"require": {
"aws/aws-sdk-php": "3.319.2"
}

2.使用代码

1.Minio.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
<?php

namespace app\common\vendor;
use Aws\S3\S3Client;


class Minio {
public $minioClient = null; // minio对象
public $minioConfig = [];//配置文件

/**
* 初始化 构造函数
* Cos constructor.
* @param array $config 配置文件信息
* @param string $prefix_url 默认的前缀
*/
public function __construct(array $config = [], $prefix_url = '') {
if (empty($config)) {
$config = Config::get('minio');
}

// 初始化cos对象
$this->minioConfig = [
'version' => $config['version'],
'region' => $config['region'],
'endpoint' => $config['endpoint'],
'use_path_style_endpoint' => $config['use_path_style_endpoint'],
'credentials' => [
'key' => $config['credentials']['key'],
'secret' => $config['credentials']['secret'],
],
'acl' => $config['acl'],
'bucket' => $config['bucket'],
];
//创建存储对象
$this->minioClient = new S3Client([
'version' => $this->minioConfig['version'],
'region' => $this->minioConfig['region'],
'endpoint' => $this->minioConfig['endpoint'],
'use_path_style_endpoint' => $this->minioConfig['use_path_style_endpoint'],
'credentials' => [
'key' => $this->minioConfig['credentials']['key'],
'secret' => $this->minioConfig['credentials']['secret']]
]
);
}

/**
* 上传文件
* @param $filestr 文件内容
* @param string $key 键值
* @param string $bucket 存储桶
* @return bool
* @author zengye
* @since 20220108 1:12
*/
public function putObject($filestr = '', $key = '', $bucket = '') {
try {
if (empty($filestr) || empty($key)) {
return false;
}
$result = $this->minioClient->putObject([
"Bucket" => $bucket ?: $this->minioConfig['bucket'],
"Key" => $key,
'Body' => $filestr,
'ACL' => $this->minioConfig['acl'],
]);
if (!$result) {
return false;
}
return $result;
} catch (S3Exception $e) {
throw new ValidateException($e->getMessage());
}
}
}

2.config.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
<?php

return [
// +----------------------------------------------------------------------
// | minio
// +----------------------------------------------------------------------
'minio' => [
'endpoint' => \think\Env::get('minio.endpoint', ''),
'version' => \think\Env::get('minio.version', ''),
'region' => \think\Env::get('minio.region', ''),
'use_path_style_endpoint' => \think\Env::get('minio.use_path_style_endpoint', true),
'credentials' => [
'key' => \think\Env::get('minio.access_key', ''),
'secret' => \think\Env::get('minio.secret_key', ''),
],
'bucket' => \think\Env::get('minio.bucket', ''),
'acl' => \think\Env::get('minio.ACL', ''),
'prefix' => \think\Env::get('minio.prefix_url', ''),
],
];

3. .env文件

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
[MINIO]
# minio地址
ENDPOINT = 'http://192.168.0.180:9000'
# minio版本
VERSION = 'latest'
# minio 地区 - 区域 设置一个默认的存储桶地域
REGION = 'us-west-2'
# minio 地区 - 区域 设置一个默认的存储桶地域
USE_PATH_STYLE_ENDPOINT = 'true'
# minio密钥accessKey
ACCESS_KEY = 'admin'
# minio密钥secretKey
SECRET_KEY = 'zgx@2021wms1234^'
# 存储桶名称 格式:BucketName-APPID
BUCKET = 'zengphp'
# 前缀url
PREFIX_URL = ''
ACL = 'public-read'

4.Config.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

namespace think;

class Config
{
/**
* @var array 配置参数
*/
private static $config = [];

/**
* @var string 参数作用域
*/
private static $range = '_sys_';

/**
* 设定配置参数的作用域
* @access public
* @param string $range 作用域
* @return void
*/
public static function range($range)
{
self::$range = $range;

if (!isset(self::$config[$range])) self::$config[$range] = [];
}

/**
* 解析配置文件或内容
* @access public
* @param string $config 配置文件路径或内容
* @param string $type 配置解析类型
* @param string $name 配置名(如设置即表示二级配置)
* @param string $range 作用域
* @return mixed
*/
public static function parse($config, $type = '', $name = '', $range = '')
{
$range = $range ?: self::$range;

if (empty($type)) $type = pathinfo($config, PATHINFO_EXTENSION);

$class = false !== strpos($type, '\\') ?
$type :
'\\think\\config\\driver\\' . ucwords($type);

return self::set((new $class())->parse($config), $name, $range);
}

/**
* 加载配置文件(PHP格式)
* @access public
* @param string $file 配置文件名
* @param string $name 配置名(如设置即表示二级配置)
* @param string $range 作用域
* @return mixed
*/
public static function load($file, $name = '', $range = '')
{
$range = $range ?: self::$range;

if (!isset(self::$config[$range])) self::$config[$range] = [];

if (is_file($file)) {
$name = strtolower($name);
$type = pathinfo($file, PATHINFO_EXTENSION);

if ('php' == $type) {
return self::set(include $file, $name, $range);
}

if ('yaml' == $type && function_exists('yaml_parse_file')) {
return self::set(yaml_parse_file($file), $name, $range);
}

return self::parse($file, $type, $name, $range);
}

return self::$config[$range];
}

/**
* 检测配置是否存在
* @access public
* @param string $name 配置参数名(支持二级配置 . 号分割)
* @param string $range 作用域
* @return bool
*/
public static function has($name, $range = '')
{
$range = $range ?: self::$range;

if (!strpos($name, '.')) {
return isset(self::$config[$range][strtolower($name)]);
}

// 二维数组设置和获取支持
$name = explode('.', $name, 2);
return isset(self::$config[$range][strtolower($name[0])][$name[1]]);
}

/**
* 获取配置参数 为空则获取所有配置
* @access public
* @param string $name 配置参数名(支持二级配置 . 号分割)
* @param string $range 作用域
* @return mixed
*/
public static function get($name = null, $range = '')
{
$range = $range ?: self::$range;

// 无参数时获取所有
if (empty($name) && isset(self::$config[$range])) {
return self::$config[$range];
}

// 非二级配置时直接返回
if (!strpos($name, '.')) {
$name = strtolower($name);
return isset(self::$config[$range][$name]) ? self::$config[$range][$name] : null;
}

// 二维数组设置和获取支持
$name = explode('.', $name, 2);
$name[0] = strtolower($name[0]);

if (!isset(self::$config[$range][$name[0]])) {
// 动态载入额外配置
$module = Request::instance()->module();
$file = CONF_PATH . ($module ? $module . DS : '') . 'extra' . DS . $name[0] . CONF_EXT;

is_file($file) && self::load($file, $name[0]);
}

return isset(self::$config[$range][$name[0]][$name[1]]) ?
self::$config[$range][$name[0]][$name[1]] :
null;
}

/**
* 设置配置参数 name 为数组则为批量设置
* @access public
* @param string|array $name 配置参数名(支持二级配置 . 号分割)
* @param mixed $value 配置值
* @param string $range 作用域
* @return mixed
*/
public static function set($name, $value = null, $range = '')
{
$range = $range ?: self::$range;

if (!isset(self::$config[$range])) self::$config[$range] = [];

// 字符串则表示单个配置设置
if (is_string($name)) {
if (!strpos($name, '.')) {
self::$config[$range][strtolower($name)] = $value;
} else {
// 二维数组
$name = explode('.', $name, 2);
self::$config[$range][strtolower($name[0])][$name[1]] = $value;
}

return $value;
}

// 数组则表示批量设置
if (is_array($name)) {
if (!empty($value)) {
self::$config[$range][$value] = isset(self::$config[$range][$value]) ?
array_merge(self::$config[$range][$value], $name) :
$name;

return self::$config[$range][$value];
}

return self::$config[$range] = array_merge(
self::$config[$range], array_change_key_case($name)
);
}

// 为空直接返回已有配置
return self::$config[$range];
}

/**
* 重置配置参数
* @access public
* @param string $range 作用域
* @return void
*/
public static function reset($range = '')
{
$range = $range ?: self::$range;

if (true === $range) {
self::$config = [];
} else {
self::$config[$range] = [];
}
}
}

5.Env.php

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php
// +----------------------------------------------------------------------
// | ThinkPHP [ WE CAN DO IT JUST THINK ]
// +----------------------------------------------------------------------
// | Copyright (c) 2006~2018 http://thinkphp.cn All rights reserved.
// +----------------------------------------------------------------------
// | Licensed ( http://www.apache.org/licenses/LICENSE-2.0 )
// +----------------------------------------------------------------------
// | Author: liu21st <liu21st@gmail.com>
// +----------------------------------------------------------------------

namespace think;

class Env
{
/**
* 获取环境变量值
* @access public
* @param string $name 环境变量名(支持二级 . 号分割)
* @param string $default 默认值
* @return mixed
*/
public static function get($name, $default = null)
{
$result = getenv(ENV_PREFIX . strtoupper(str_replace('.', '_', $name)));

if (false !== $result) {
if ('false' === $result) {
$result = false;
} elseif ('true' === $result) {
$result = true;
}

return $result;
}

return $default;
}
}

6.调用minio

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
public function cosFiles() {
$file = request()->file('image');
$file_prefix = request()->post('prefix');
$file_type = request()->post('type',self::UPLOADS_TYPES_IMAGE);
if (!$file)
$file = request()->file('file');
if (!$file) return return_ajax(400, '文件不存在');
$s = $file->getInfo();
if (!$s) return return_ajax(400, '文件错误');
$n = explode('.', $s['name']);
if (!$n || count($n) == 1) return return_ajax(400, '没有后缀名');
//初始化minio对象
$cos = new Minio(\config('minio'));

$filestr = fopen($s['tmp_name'], 'rb');
if (!$filestr) return return_ajax(400, '读取文件错误');
$day = date('Y_m_d');
// 上传文件流
try {
$key = 'newUploads/' . ($file_prefix && strlen($file_prefix) > 0 ? $file_prefix . '/' : '') . $day . '/' . time() . '_' . rand(1, 100000) . '.' . $n[1];
$result = $cos->putObject($filestr, $key);
if (!$result) {
return return_ajax(400, '没有数据');
}

// 视频类型
$prefix_url = '';
if($file_type == self::UPLOADS_TYPES_VIDEO) {
$prefix_url = Config::get('static_url');
}

return return_ajax(200, '上传ok', [
'url' => $result['ObjectURL'],
'result' => $result
]);
} catch (\Exception $e) {
return return_ajax(400, '错误');
}
}

3.参考文档

1
https://blog.csdn.net/WZP_LOVE/article/details/115208900

php集成minio
http://example.com/2025/04/16/php集成minio/
作者
zgx
发布于
2025年4月16日
许可协议