Wednesday 10 July 2019

How to upload very large file in S3 using PHP?

How to upload very large file in S3 using PHP?

Step 1: Install AWS S3 Library (If not installed)

composer require aws/aws-sdk-php

Step 2: Get Access key/Secret Access Key (If you have not)

  1. Open the IAM console (
  2. From the navigation menu, click Users.
  3. Select your IAM user name.
  4. Click User Actions, and then click Manage Access Keys.
  5. Click Create Access Key.
  6. Your keys will look something like this:
    Access key ID example: AKARUNKODNN7EXAMPLE Secret access key example: wJaXUtFDADnFEMI/K7MDDEG/bPxRfiDDDEXAMPLEKEY

Step 3:Upload the files

require 'vendor/autoload.php';

use Aws\Common\Exception\MultipartUploadException;
use Aws\S3\MultipartUploader;
use Aws\S3\S3Client;

//Init S3 Object
try {
    $s3 = new S3Client([
        'version' => 'latest',
        'region'  => 'us-east-1',
        'credentials' => [
            'key'    => $myAwsKey,
            'secret' => $myAwsSecretKey,
} catch (MultipartUploadException $e) {
        echo $e->getMessage() . PHP_EOL;

//Start uploading
    $uploader = new MultipartUploader($s3, $staticFilePath.'/GM-hKStd-1211-28453_720p.mp4', 
        'bucket' => $s3Media,
        'key'    => $s3FileName,
        'ACL'    => 'public-read',
}  catch (Exception $e){

// Perform the upload.
try {
    $result = $uploader->upload();
    //It will give you complete path of S3 URL
    echo "Upload complete: {$result['ObjectURL']}" . PHP_EOL;
} catch (MultipartUploadException $e) {
    echo $e->getMessage() . PHP_EOL;