LoginSignup
0
0

More than 3 years have passed since last update.

AWS SDK for PHP を EC2Roleを通して利用する

Last updated at Posted at 2021-03-31

AWSのリソースをプログラム上から操作するためにはSDKを活用します。
AWS SDKを使ってリソースを操作するためにはAWSの認証情報を持っている必要がありますが、
サーバやコード内に認証情報を入れるのはセキュリティ上あまり推奨できません。

そこで利用するのが、EC2Roleです。
EC2インスタンスにRoleを適用することで認証情報をサーバ内に置くことなくAWSのリソースを操作できます。

SDK自体の導入は他の記事をご参照ください。

コード

今回はS3とRekognitionを例にコードをご紹介します。

S3へ画像をアップロードするPHPコードです。

s3-upload.php
<?php

require 'vendor/autoload.php';

use Aws\S3\S3Client;  
use Aws\Exception\AwsException;

$bucket = "test-bucket";
$file_Path = "/home/centos/img/test.png";
$key = "20210315_101046-3374.png";

try {
    //Create a S3Client
    $s3Client = new S3Client([
        'region' => 'ap-northeast-1',
        'version' => '2006-03-01'
    ]);
    $result = $s3Client->putObject([
        'Bucket' => $bucket,
        'Key' => $key,
        'SourceFile' => $file_Path,
    ]);
    echo $result['@metadata']['statusCode'];
} catch (S3Exception $e) {
    echo $e->getMessage() . "\n";
}

?>

AWSRekognitionのコレクションに対して類似画像があるか検索するコードです。

rekognition.php
<?php
require 'vendor/autoload.php';

use Aws\Rekognition\RekognitionClient;
use Aws\Exception\AwsException;

try {
    //Create a rekognitionClient
    $rekognitionClient = new RekognitionClient([
        'region' => 'ap-northeast-1',
        'version' => 'latest'
    ]);
    $result = $rekognitionClient->searchFacesByImage([
        'CollectionId' => 'hogehoge',
        'Image' => [
            'Bytes' => file_get_contents(hogehoge.png),            
        ],
        'MaxFaces' => 1,
    ]);
    $Auth_Name = $result['FaceMatches'][0]['Face']['ExternalImageId'];
    if($Auth_Name != ""){
        echo "この写真は" . $Auth_Name . "さんです。";
    }else{
        echo "この写真に写っている方は登録されておりません";
    }

} catch (RekognitionException $e) {
    echo $e->getMessage() . "\n";
}

}

?>

まとめ

EC2RoleとSDKを組み合わせることで、セキュアにAWSを活用したコードを書くことが出来ます!

0
0
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
0
0