LoginSignup
11
4

More than 5 years have passed since last update.

S3Clientクラス(AWS SDK for PHP 3.x)

Last updated at Posted at 2017-10-17

下準備

AWS SDK for PHPを下記コマンドでインストール

php composer.phar require aws/aws-sdk-php

設定

S3Controller

use Aws\S3\S3Client;

public function initialize(array $config)
    {
        $this->config = [
            's3' => [
                'key' => 'key', //S3アクセスのためのキー
                'secret' => 'secret', //S3アクセスのためのシークレットキー
                'bucket' => 'bucket', //S3バケット名
            ]
        ];

        $this->s3 = S3Client::factory([
                    'credentials' => [
                        'key' => $this->config['s3']['key'],
                        'secret' => $this->config['s3']['secret']
                    ],
                    'region' => 'ap-northeast-1', //リージョンは日本
                    'version' => 'latest' //バケットのバージョニングは最新
        ]);
    }


シンプルなサンプル

ファイルアップロード

$result = $this->s3->putObject([
            'Bucket' => $this->config['s3']['bucket'],
            'Key' => 'test/img.jpg', //アップロード先のフォルダとファイル名を指定
            'SourceFile' => $imgData['tmp_name'],
            'StorageClass' => 'REDUCED_REDUNDANCY' //低冗長化モードを指定
        ]);

リスト取得

//オブジェクト型で取得
$list = $this->s3->listObjects([
         'Bucket' => $this->config['s3']['bucket'],
         'MaxKeys' => 10, //最大取得数
         'Prefix' => 'folder' //フォルダ指定
        ]);

//下記コードでフォルダと画像名のみ取得する
foreach ($list['Contents'] as $img) {
      $result[] = $img['Key'];
}

画像削除

$result = $this->s3->deleteObject([
            'Bucket' => $this->config['s3']['bucket'],
            'Key' => 'test/deleted.jpg']//削除対象を指定
          );

他にも様々な機能があるので、確認して見てください。
http://docs.aws.amazon.com/aws-sdk-php/v3/api/class-Aws.S3.S3Client.html#_factory

11
4
0

Register as a new user and use Qiita more conveniently

  1. You get articles that match your needs
  2. You can efficiently read back useful information
  3. You can use dark theme
What you can do with signing up
11
4