How to work with S3 using the AWS SDK client in php

 0. Install php

1. INSTALL composer

Go to the directory from which we will work with php..
Load composer.phar

2. INSTALL aws/aws-sdk-php PACKAGE

php composer.phar require aws/aws-sdk-php


3. GET PROFILE DATA

Log in to the service administration panel at: https://cmc.objstor.cloud4u.com:8443/ using your credentials received from Cloud4U technical support after purchasing the service or from your S3 administrator.


S3 AWS

 

In the administration panel, in the profile properties, find out and remember (write down) ACCESS KEY ID, SECRET KEY

S3 AWS


4. CREATE PHP FILE, SPECIFY KEY AND SECRET, INITIATE S3CLIENT OBJECT

<?php

require 'vendor/autoload.php';

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

#Create an s3 instance
$s3 = new S3Client([
    'version' 	=> 'latest',
    'region'  	=> 'msk',
    'use_path_style_endpoint' => true,
    'credentials' => [
        'key'	=> 'KEY',
        'secret' => 'SECRET',
    ],
    'endpoint' => 'https://s3.objstor.cloud4u.com'
]);


5. CREATE bucket

<?php

#Create bucket via api
$s3->createBucket(['Bucket' => 'my-new-bucket']);


#Check if the new bucket has appeared in the general list
$listBuckets = $s3->listBuckets();
echo '<pre>';
var_export($listBuckets->toArray()['Buckets']);
echo '</pre>';


THE bucket IS SUCCESSFULLY CREATED

S3 AWS


ALL OF THE ABOVE ACTIONS, WE CAN ALSO CHECK IN THE CONTROL PANEL


6. ADD AN OBJECT TO THE bucket

<?php

#Load the object from the line
$s3->putObject([
    'Bucket' => 'my-new-bucket',
    'Key' => 'MyNewObjectForDelete',
    'Body' => 'MyObjectBody1',
]);

#Get an object
$result = $s3->getObject([
    'Bucket' => 'my-new-bucket',
    'Key' => 'MyNewObjectForDelete'
]);

echo '<pre>';
var_export($result->toArray());
echo '</pre>';

After running the php script we see that the object has been created

S3 AWS


7. DELETE AN OBJECT 

<?php

echo '<h2>Before</h2>';
#Get a list of objects
$result = $s3->listObjects([
    'Bucket' => 'my-new-bucket'
]);
echo '<pre>';
var_export($result->toArray()['Contents']);
echo '</pre>';


#Delete an object
$s3->deleteObject([
    'Bucket' => 'my-new-bucket',
    'Key' => 'MyNewObjectForDelete'
]);


echo '<h2>After</h2>';
#Get a list of objects
$result = $s3->listObjects([
    'Bucket' => 'my-new-bucket'
]);
echo '<pre>';
var_export($result->toArray()['Contents']);
echo '</pre>';

out of two objects, there is one left


8. OBJECT UPLOAD WITH MULTIPARTUPLOADER, SUITABLE FOR FILES FROM 5MB TO 5TB

<?php

#Using stream instead of file path
    $source = './bff-107mb.zip';
    $uploader = new MultipartUploader($s3, $source, [
        'bucket' => $bucketName,
        'key' => 'my-file.zip',
    ]);
#Error recovery
    do {
        try {
            $result = $uploader->upload();
        } catch (MultipartUploadException $e) {
            $uploader = new MultipartUploader($s3, $source, [
                'state' => $e->getState(),
            ]);
        }
    } while (!isset($result));

# Abort a download if it fails
    try {
        $result = $uploader->upload();
    } catch (MultipartUploadException $e) {
#State includes "Bucket", "Key", "UploadId"
        $params = $e->getState()->getId();
        $result = $s3->abortMultipartUpload($params);
    }

    echo '<pre>';
    var_export($result->toArray());
    echo '</pre>';
}


9. If you are not sure whether to use PutObject or MultipartUploader to upload an object, use ObjectUploader. ObjectUploader will upload a large file to S3 using PutObject or MultipartUploader, making its own choice based on the size of the object.

<?php

$source = fopen('./bff-107mb.zip', 'rb');

$uploader = new ObjectUploader(
    $s3,
    'my-new-bucket',
    'file.zip',
    $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($s3, $source, [
            'state' => $e->getState(),
        ]);
    }
} while (!isset($result));

fclose($source);


10. ThE File IS successfully uploaded.

Find more information about aws-sdk-php at github

 

Have you tried Virtual cloud servers by Cloud4U? Not yet?

Leave a request and get 10 days free trial access..

Have you tried Cloud4U cloud services? Not yet?

Go to the Main Website

Try for free

  • 28 Users Found This Useful
Was this answer helpful?

Related Articles

7. Billing in S3 Object Storage

  Billing in S3 includes the following parameters The amount of space used Number of...

4.Способы работы с объектным хранилищем через различное программное обеспечение

Подготовка идентификационных данных 1. Авторизуйтесь в объектном хранилище Cloud4Y:...

3.Storage and data access management in S3 Object Storage

1.Organization of data storage in S3 object storageS3 is not a hierarchical file system, but...

Access to S3 from the VCD cloud dashboard

The VMware vCloud Director® Object Storage Extension™ plug-in enables Cloud4U users to access...

Getting Started with S3 Cloud4U Using the AWS CLI

1) Install AWS CLI - On Windows, load AWSCLI-64 or AWSCLI-32 bit installer for Windows and set...