前提
・コンポーザーで以下が入っている。
composer require aws/aws-sdk-php
・copnfig/app.phpなどAWS用のライブラリ設定済み(以下のもの)
'providers' => array(
// ...
Aws\Laravel\AwsServiceProvider::class,
)
'aliases' => array(
// ...
'AWS' => Aws\Laravel\AwsFacade::class,
)
・ config/aws.php設定済み (こういうの)
<?php
use Aws\Laravel\AwsServiceProvider;
return [
/*
*/
'credentials' => [
'key' => env('AWS_ACCESS_KEY_ID', ''),
'secret' => env('AWS_SECRET_ACCESS_KEY', ''),
],
'region' => env('AWS_REGION', 'us-east-1'),
'version' => 'latest',
'ua_append' => [
'L5MOD/' . AwsServiceProvider::VERSION,
],
];
- AWSコンソールからアクセスキーとシークレットアクセスキーを取得
・サービスからIAMへ
・メニューからユーザを選択
・ セキュリティー認証情報からアクセスキーを作成
→ csvがダウンロードできる
・laravelへ設定
.envにそれぞれ設定
AWS_ACCESS_KEY_ID=
AWS_SECRET_ACCESS_KEY=
以下のようなコードでS3からデータ取得できる
<?php
namespace App\Console\Commands;
use Aws\S3\S3Client;
use Config;
use Illuminate\Console\Command;
class LoanInitialRate extends Command
{
/**
* The name and signature of the console command.
*
* @var string
*/
protected $signature = 'import:loan_initial_rate';
/**
* The console command description.
*
* @var string
*/
protected $description = 'Command description';
/**
* Execute the console command.
*
* @return int
*/
public function handle()
{
$s3 = new S3Client([
'credentials' => Config::get('aws.credentials'), // aws上では省いたほうが良さそうなのでちょっとそこはわけたほうがよいかも(推測)
'version' => 'latest',
'region' => 'ap-northeast-1'
]);
$s3_list = $s3->ListObjects([
'Bucket' => 'example-s3',//バケット名
'Prefix' => "fileno_",//ファイル指定
]);
foreach ($s3_list['Contents'] as $object) {
echo "ファイル名: " . $object['Key'] . "\n";
// 各ファイルの内容を取得
$file = $s3->getObject([
'Bucket' => 'example-s3',
'Key' => $object['Key']
]);
// ファイル内容を表示
$content = $file['Body']->getContents();
echo $content . "\n";
}
}
}