LoginSignup
4
5

More than 3 years have passed since last update.

PHPでS3からファイル一覧を取得する

Last updated at Posted at 2020-09-02

使う機会あると思うのですが、
依存関係とかそういったものを意識せずに使えるコードが無かったので。

準備

console
% composer require aws/aws-sdk-php
# 中略

% touch get.php

% tree -L 1
.
├── composer.json
├── composer.lock
├── get.php
└── vendor

ユーザやバケットは作成してあり、画像が格納されている前提です。

コード

get.php
<?php
declare(strict_types=1);

require_once __DIR__ . '/vendor/autoload.php';

use Aws\S3\S3Client;

define('REGION', 'ap-northeast-1');
define('BASE_URL', sprintf('https://s3-%s.amazonaws.com/', REGION));
define('BUCKET_NAME', 'bucket_name');

$s3 = new S3Client([
    'version' => 'latest',
    'credentials' => [
        'key' => 'mykey',
        'secret' => 'mysecret',
    ],
    'region' => REGION,
]);

// S3バケットの画像を全て取得
$objectContent = $s3->listObjects([
    'Bucket' => BUCKET_NAME,
    'Prefix' => 'path/to/file/',
])['Contents'];

// URLを組み立ててHTML生成
foreach ($objectContent as $object) {
    // ここで$object['Key']の拡張子で処理分けたらもっと良いかも
    echo sprintf("<img src=\"%s%s/%s\" width=\"300\"><br>", BASE_URL, BUCKET_NAME, $object['Key']);
}

参考

4
5
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
4
5