티스토리 뷰

PROGRAMMING

[PHP] AWS S3에 파일 업로드하기

비용러브 2023. 5. 17. 20:18

1. AWS SDK FOR PHP 설치

AWS에서는 AWS SDK를 설치할 수 있는 3가지 방법을 안내하고 있습니다.

AWS SDK PHP 참고 : https://docs.aws.amazon.com/aws-sdk-php/v3/guide/getting-started/installation.html

 

Installing the AWS SDK for PHP Version 3 - AWS SDK for PHP

Using PHP with the Suhosin patch is not recommended, but is common on Ubuntu and Debian distributions. In this case, you might need to enable the use of phars in the suhosin.ini. If you don’t do this, including a phar file in your code will cause a silen

docs.aws.amazon.com

2. PHP 코드 작성

<?php
define('S3_KEY', '.....');
define('S3_SECRET_KEY', '.....');
define('BUCKET', '.....');
include_once('aws/aws-autoloader.php');
// 앞서 다운로드한 SDK 파일의 autoloader를 불러옵니다.
 
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
// S3 파일 업로드에 필요한 클래스를 불러옵니다.
 
$s3Client = S3Client::factory(array(
  'region' => 'ap-northeast-2',
  'version' => 'latest',
  'signature' => 'v4',
  'key'    => S3_KEY,
  'secret' => S3_SECRET_KEY
));
// AWS IAM 에서 등록한 사용자의 Key와 Secret key로 서울 리전('ap-northeast-2')의 S3로 접근합니다.
 
$file_url = 'https://xxxx.net/img.png';
$s3_path = '/img/img.png';
$file_data = file_get_contents($file_url);
 
$s3Client->putObject(array(
  'Bucket' => BUCKET,
  'Key'    => $s3Path,
  'Body'   => $file_data,
  'ACL'    => 'public-read'
));
// 이미지 파일('https://falsy.me/img/logo.png')을 S3버킷의 img디렉토리 안에 저장합니다.
?>

3. 마치며

S3 region 참고 : https://docs.aws.amazon.com/ko_kr/general/latest/gr/rande.html#s3_region

 

AWS 서비스 엔드포인트 - AWS 일반 참조

이 페이지에 작업이 필요하다는 점을 알려 주셔서 감사합니다. 실망시켜 드려 죄송합니다. 잠깐 시간을 내어 설명서를 향상시킬 수 있는 방법에 대해 말씀해 주십시오.

docs.aws.amazon.com

 

서울 리전을 사용하면 서명 버전을 v4 만 사용이 가능

<?php
$s3Client = S3Client::factory(array(
  'region' => 'ap-northeast-2',
  'version' => 'latest',
  'credentials' => array(
    'key' => '*********',
    'secret' => '***********************'
  )
));
?>
<?php
$s3Client = S3Client::factory(array(
  'region' => 'ap-northeast-2',
  'version' => 'latest',
  'signature' => 'v4',
  'key'    => '**********',
  'secret' => '**********************'
));
?>

 

댓글