如何使用AWS SDK for PHP操作Minio Server Slack

aws-sdk-php是PHP语言版本的官方AWS SDK。本文我们将学习如何使用aws-sdk-php来操作Minio Server。

1. 前提条件

这里下载并安装Minio Server。

2. 安装

AWS SDK for PHP官方文档下载将安装aws-sdk-php

3. 使用GetObject和PutObject

下面示例描述的是如何使用aws-sdk-php对Minio Server进行putObject和getObject操作。请将example.php文件中的endpoint,key, secret, Bucket修改为你的本地配置。注意,我们将use_path_style_endpoint设置为true以使用AWS SDK for PHP来操作Minio。了解更多,请参考AWS SDK for PHP

<?php

// 使用Composer autoloader引入SDK
date_default_timezone_set('America/Los_Angeles');
require 'vendor/autoload.php';

$s3 = new Aws\S3\S3Client([
        'version' => 'latest',
        'region'  => 'us-east-1',
        'endpoint' => 'http://localhost:9000',
        'use_path_style_endpoint' => true,
        'credentials' => [
                'key'    => 'YOUR-ACCESSKEYID',
                'secret' => 'YOUR-SECRETACCESSKEY',
            ],
]);


// 发送PutObject请求并获得result对象
$insert = $s3->putObject([
     'Bucket' => 'testbucket',
     'Key'    => 'testkey',
     'Body'   => 'Hello from Minio!!'
]);

// 下载文件的内容
$retrive = $s3->getObject([
     'Bucket' => 'testbucket',
     'Key'    => 'testkey',
     'SaveAs' => 'testkey_local'
]);

// 通过索引到结果对象来打印结果的body。
echo $retrive['Body'];

修改之后,运行程序

php example.php
Hello from Minio!!

4. 生成pre-signed URL

<?php
// 从client中获得一个commad对象
$command = $s3->getCommand('GetObject', [
            'Bucket' => 'testbucket',
            'Key'    => 'testkey'
        ]);

// 获得一个10分钟有效期的pre-signed URL
$presignedRequest = $s3->createPresignedRequest($command, '+10 minutes');

// 获得presigned-url
$presignedUrl =  (string)  $presignedRequest->getUri();

5. 获取plain URL

获取一个plain URL,你需要将你的object/bucket权限设为public。注意,你不会获得带有后面这些信息的URL,X-Amz-Algorithm=[...]&X-Amz-Credential=[...]&X-Amz-Date=[...]&X-Amz-Expires=[...]&X-Amz-SignedHeaders=[...]&X-Amz-Signature=[...]

<?php
$plainUrl = $s3->getObjectUrl('testbucket', 'testkey');

6. 设置存储桶策略

<?php
$bucket = 'testbucket';
// 该策略设置存储桶为只读
$policyReadOnly = '{
  "Version": "2012-10-17",
  "Statement": [
    {
      "Action": [
        "s3:GetBucketLocation",
        "s3:ListBucket"
      ],
      "Effect": "Allow",
      "Principal": {
        "AWS": [
          "*"
        ]
      },
      "Resource": [
        "arn:aws:s3:::%s"
      ],
      "Sid": ""
    },
    {
      "Action": [
        "s3:GetObject"
      ],
      "Effect": "Allow",
      "Principal": {
        "AWS": [
          "*"
        ]
      },
      "Resource": [
        "arn:aws:s3:::%s/*"
      ],
      "Sid": ""
    }
  ]
}
';
// 如果你想将文件放到指定目录,你只需要修改'arn:aws:s3:::%s/*'为'arn:aws:s3:::%s/folder/*'

// 创建一个存储桶
$result = $s3->createBucket([
    'Bucket' => $bucket,
]);

// 配置策略
$s3->putBucketPolicy([
    'Bucket' => $bucket,
    'Policy' => sprintf($policyReadOnly, $bucket, $bucket),
]);