본 수업은 PHP SDK를 이용해서 S3를 이용하는 방법에 대한 수업입니다.
선수학습
본 수업은 AWS SDK for PHP 수업을 먼저 들으셔야 합니다.
권한
본 수업을 진행하기 위해서는 사용자나 역할이 AmazonS3FullAccess 권한이 있어야 합니다.
API 사용법
파일 전송
s3_put.php
1 2 3 4 5 6 7 8 9 10 11 | <?php require 'vendor/autoload.php' ; $param = Array( 'region' => 'ap-northeast-2' , 'version' => '2006-03-01' ); $s3 = new Aws\S3\S3Client( $param ); $s3 ->putObject(Array( 'ACL' => 'public-read' , 'SourceFile' => 'sample.txt' , 'Bucket' => 'codingeverybody2' , 'Key' => 'sample.txt' )); ?> |
파일 목록 가져오기
s3_list.php
1 2 3 4 5 6 7 8 9 10 | <?php require 'vendor/autoload.php' ; $param = Array( 'region' => 'ap-northeast-2' , 'version' => '2006-03-01' ); $s3 = new Aws\S3\S3Client( $param ); $list = $s3 ->listObjects(Array( 'Bucket' => 'codingeverybody2' )); $listArray = $list ->toArray(); foreach ( $listArray [ 'Contents' ] as $item ){ print ( $item [ 'Key' ]. "\n" ); } ?> |
파일 다운로드
s3_get.php
1 2 3 4 5 6 7 8 9 | <?php require 'vendor/autoload.php' ; $param = Array( 'region' => 'ap-northeast-2' , 'version' => '2006-03-01' ); $s3 = new Aws\S3\S3Client( $param ); $s3 ->getObject(Array( 'Bucket' => 'codingeverybody2' , 'Key' => 'sample.txt' , 'SaveAs' => fopen ( 'sample_saved.txt' , 'w' ) )); |
웹애플리케이션에서 S3 활용
업로드 폼
upload.html
1 2 3 4 5 6 7 8 | < html > < body > < form enctype = "multipart/form-data" action = "./s3_upload.php" method = "POST" > < input type = "file" name = "userfile" > < input type = "submit" > </ form > </ body > </ html > |
s3로 파일 전송
s3_upload.php
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 | <?php require 'vendor/autoload.php' ; $param = Array( 'region' => 'ap-northeast-2' , 'version' => '2006-03-01' ); $s3 = new Aws\S3\S3Client( $param ); $result = $s3 ->putObject(Array( 'ACL' => 'public-read' , 'SourceFile' => $_FILES [ 'userfile' ][ 'tmp_name' ], 'Bucket' => 'codingeverybody2' , 'Key' => $_FILES [ 'userfile' ][ 'name' ], 'ContentType' => $_FILES [ 'userfile' ][ 'type' ] )); unlink( $_FILES [ 'userfile' ][ 'tmp_name' ]); $resultArray = $result ->toArray(); var_dump( $resultArray [ 'ObjectURL' ]); ?> <html> <body> <img src= "<?php print($resultArray['ObjectURL']);?>" style= "width:100%" > </body> </html> |