vishavjeet

singh.vishavjeet11@gmail.com

How to upload file on AWS S3 Bucket CDN using PHP CodeIgniter

Posted on February 12, 2021



#Step1: Create Aws3 class which file path application/libraries/Aws3.php

Source Code:

<?php if (!defined('BASEPATH')) exit('No direct script access allowed');

include("./vendor/autoload.php");

use Aws\S3\S3Client;

use Aws\Exception\AwsException;

class Aws3{

private $S3;

public function __construct(){

$this->S3 = S3Client::factory([

'key' => 'XXXXXXX',

'secret' => 'XXXXXXX',

'region' => 'ap-south-1'

]);

}

    public function addBucket($bucketName){

    $result = $this->S3->createBucket(array(

    'Bucket'=>$bucketName,

    'LocationConstraint'=> 'ap-south-1'));

    return $result;

   }

  public function sendFile($bucketName, $file_path, $filename){

  $bucketName='vishavjeet-s3-repo';

   $result = $this->S3->putObject(array(

   'Bucket' => $bucketName,

   'Key' => $file_path,

  'SourceFile' => $filename['tmp_name'],

  'ContentType' => 'image/png',

  'StorageClass' => 'STANDARD',

   'ACL' => 'public-read'

  ));

return $result['ObjectURL']."\n";

}

  public function uploadfile_s3($keyName,$file)

  {

      $bucketName = 'vishavjeet-s3-repo';

     $IAM_KEY = 'XXXXX';

    $IAM_SECRET = 'XXXXXX';

    try {

       $s3 = S3Client::factory(

    array(

        'credentials' => array(

        'key' => $IAM_KEY,

       'secret' => $IAM_SECRET

      ),

   'version' => 'latest',

   'region' => 'ap-south-1'

    )

 );

} catch (Exception $e) { 

    die("Error: " . $e->getMessage()); 

  }

  try {

     $s3->putObject(

     array(

         'Bucket'=>$bucketName,

         'Key' => $keyName,

         'ACL' => 'public-read',

        'CacheControl' => 'max-age=172800',

        "Expires"=> gmdate("D, d M Y H:i:s T", strtotime("+7 days")),

        'SourceFile' =>$file,

        /*'StorageClass' => 'REDUCED_REDUNDANCY'*/

         )

     );

   } catch (S3Exception $e) {

        die('Error:' . $e->getMessage());

     } catch (Exception $e) {

           die('Error:' . $e->getMessage());

         }

      }

}


#Step2: load library in Controller

class Product_Api extends CI_Controller

{

      public function __construct()

     {

        parent::__construct();

       $this->load->library('aws3');

        date_default_timezone_set('Asia/Kolkata');

    }

  public function addImage()

  {

         $keyName = 'uploads/product/'.$product_id.'/'.$_FILES[$filename]['name'];

         $file = $_FILES[$filename]['tmp_name'];

      $response=$this->uploadfile_s3($keyName,$file)

   }

}


Sign In for comment and like the post.