kyoagunのブログ

技術系、PdMについてを書いていこうと思います。

PHPでAWSのS3へファイルをアップしてみる

■プロジェクト作成
mkdir delivery

■プロジェクトの初期化
composer init

aws-sdk-phpのインストール
composer require aws/aws-sdk-php

aws-sdk-phpを使うための環境設定
Linuxを想定
export AWS_ACCESS_KEY_ID=AKIAIOSFODNN7EXAMPLE
export AWS_SECRET_ACCESS_KEY=wJalrXUtnFEMI/K7MDENG/bPxRfiCYEXAMPLEKEY
export AWS_DEFAULT_REGION=us-west-2

■アップロード用のファイル作成
touch contens-to-s3.php

■contens-to-s3.phpを開いて、ライブラリーをインクルード

■アップロードと、ダウンロードをしてみる
<?php
require './vendor/autoload.php';

use Aws\S3\S3Client;

use Aws\Exception\AwsException;

// Create a S3Client
$sharedConfig = [
'version' => 'latest',
'region' => 'ap-northeast-1'
];

// Create an SDK class used to share configuration across clients.
$sdk = new Aws\Sdk($sharedConfig);

// Create an Amazon S3 client using the shared configuration data.
$client = $sdk->createS3();

// Send a PutObject request and get the result object.
$result = $client->putObject([
'Bucket' => 'content-upload-s3',
'Key' => 'my-key',
'Body' => 'this is the body!'
]);

// Download the contents of the object.
$result = $client->getObject([
'Bucket' => 'content-upload-s3',
'Key' => 'my-key'
]);

var_dump($result['Body']);

これで、結果が表示されれば完了です。