본문 바로가기

php 헛다리/CI4 헛다리

ci4 - aws s3 파일업로드

728x90

 

 

https://huningyo.tistory.com/290

 

aws CDN 001 - s3 버킷생성

모든서비스 - 스토리지 - s3​​진행전 지역을 버지니아 북부로 진행하자.https 를 사용하려면 버지니아 북부만 가능한다. http만 사용한다면 버지니아 북부를 하지 않아도 된다.하지만 문제가 생

huningyo.tistory.com

 

 

https://huningyo.tistory.com/291

 

aws CDN 002 - cloudFront (s3 버킷을 cloudFront에 연결)

https://huningyo.tistory.com/290 aws CDN 001 - s3 버킷생성모든서비스 - 스토리지 - s3​​진행전 지역을 버지니아 북부로 진행하자.https 를 사용하려면 버지니아 북부만 가능한다. http만 사용한다면 버지니

huningyo.tistory.com

 

 

os: 우분투 서버 24.04

ssh 접속

#> cd 프로젝트 이동

composer 미설치시

#> apt install composer

필요시

#> sudo apt-get install php-xml

#> composer require aws/aws-sdk-php

 

###  .env
AWS_ACCESS_KEY_ID=your_access_key_id // IAM 에서 생성한 키
AWS_SECRET_ACCESS_KEY=your_secret_access_key // IAM 에서 생성한 키
AWS_DEFAULT_REGION=ap-northeast-2
AWS_BUCKET_NAME=your_bucket_name // s3 버킷명

 

예제
<?php

namespace App\Services;

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

class AwsS3Service
{
    protected $s3;

    public function __construct()
    {
        $this->s3 = new S3Client([
            'version'     => 'latest',
            'region'      => getenv('AWS_DEFAULT_REGION'),
            'credentials' => [
                'key'    => getenv('AWS_ACCESS_KEY_ID'),
                'secret' => getenv('AWS_SECRET_ACCESS_KEY'),
            ]
        ]);
    }

    // 파일 업로드
    public function uploadFile($filePath, $key)
    {
        try {
            $result = $this->s3->putObject([
                'Bucket'     => getenv('AWS_BUCKET_NAME'),
                'Key'        => $key,  // S3에 업로드될 파일 경로
                'SourceFile' => $filePath,
                'ACL'        => 'public-read', // 공개 읽기 권한
            ]);
            return $result['ObjectURL'];  // 업로드된 파일 URL 반환
        } catch (AwsException $e) {
            return $e->getMessage(); // 오류 메시지 반환
        }
    }

    // 파일 삭제
    public function deleteFile($key)
    {
        try {
            $this->s3->deleteObject([
                'Bucket' => getenv('AWS_BUCKET_NAME'),
                'Key'    => $key,
            ]);
            return true;
        } catch (AwsException $e) {
            return $e->getMessage();
        }
    }
}
728x90