Tom
Tom

Reputation: 759

Uploading Objects to AWS S3 with SDK 3 for PHP

For many years my PHP application has used the AWS SDK 2 for PHP and now we are considering switching to SDK 3.

However, looking in the SDK documentation we couldn't find any simple example, they all talk about multipart and other things that are very different from what we have today.

The code below is what we have for SDK 2, how would a simple object be uploaded to a bucket using SDK3?

<?php

define('S3_KEY',            '');
define('S3_SECRET',         '');
define('S3_BUCKET_NAME',    '');

$s3 = S3Client::factory(array(
    'key'       => S3_KEY,
    'secret'    => S3_SECRET
));

$filename = 'example/001/1.jpg';

try {
    $resource = fopen($origin, 'r');
    $return = $s3->upload(S3_BUCKET_NAME, $filename, $resource, 'public-read');
    return $return['ObjectURL'];
} catch (S3Exception $e) {
    return false;
}

Upvotes: 0

Views: 438

Answers (1)

Arpit Jain
Arpit Jain

Reputation: 4043

In AWS SDK for PHP Version 3, ObjectUploader can upload a file to Amazon S3 using either PutObject or MultipartUploader, depending on what is best based on the payload size.

Below is the sample code, you can use to upload objects into the S3 bucket:-

require 'vendor/autoload.php';

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

$s3Client = new S3Client([
    'profile' => 'default',
    'region' => 'us-east-2',
    'version' => '2006-03-01'
]);

$bucket = 'your-bucket';
$key = 'my-file.zip';

// Using stream instead of file path
$source = fopen('/path/to/file.zip', 'rb');

$uploader = new ObjectUploader(
    $s3Client,
    $bucket,
    $key,
    $source
);

do {
    try {
        $result = $uploader->upload();
        if ($result["@metadata"]["statusCode"] == '200') {
            print('<p>File successfully uploaded to ' . $result["ObjectURL"] . '.</p>');
        }
        print($result);
    } catch (MultipartUploadException $e) {
        rewind($source);
        $uploader = new MultipartUploader($s3Client, $source, [
            'state' => $e->getState(),
        ]);
    }
} while (!isset($result));

fclose($source);

From Version 3 of the SDK Key differences:

  1. Use new instead of factory() to instantiate the client.
  2. The 'version' and 'region' options are required during instantiation.

Upvotes: 1

Related Questions