Do you want to upload files to Amazon S3 programmatically? Amazon S3 is a cloud storage service where one can store files, images, or any kind of documents. You can make these documents available publicly or can be stored as private depending on your choice. In this article, we study how to upload files to Amazon S3 using the official AWS PHP SDK library.
Amazon S3 provides high-scalable object storage. Because of its robustness and performance, it is a popular cloud storage service among people.
Why Need to Upload Files On Amazon S3?
Well, there are several reasons to keep your files on Amazon S3. I would recommend using cloud storage wherever possible for disaster recovery. As it’s a cloud-based service, you can access your files from anywhere. Using this service, users can keep their documents confidential. AWS provides you with a feature to keep your document either public or private. Secondly, if you are running a website then keeping your files(images, PDFs, etc.) on the cloud will save you a lot of bandwidth. It saves your hosting space and reduces the loads on your server.
That being said, let’s take a look at how to upload files on Amazon S3 using PHP.
Get Your Security Credentials
To get started with S3, you should have an account on AWS. Upon creating an account, activate the service S3 by following their verification process.
After activating the S3 service, get the security credentials that we will require for API integration.
Code for Uploading Files to Amazon S3
You are ready with AWS API keys. Next, install an official AWS PHP SDK library into your project. I recommend using Composer for installation. Open the terminal in your project root directory and run the below command.
composer require aws/aws-sdk-php
This command will install the library with its dependencies to your project.
Create Amazon S3 Bucket
In AWS, all objects(documents) are stored inside the Bucket. The bucket is nothing but a logical unit of storage. You can create as many Buckets and organize your documents.
You will find the option to create a bucket on the S3 dashboard directly. But if someone is looking to create it dynamically then refer to the code below.
create-bucket.php
<?php
require 'vendor/autoload.php';
use Aws\S3\S3Client;
$bucket = 'YOUR_BUCKET_NAME';
$s3Client = new S3Client([
'version' => 'latest',
'region' => 'YOUR_AWS_REGION',
'credentials' => [
'key' => 'ACCESS_KEY_ID',
'secret' => 'SECRET_ACCESS_KEY'
]
]);
try {
$result = $s3Client->createBucket([
'Bucket' => $bucket, // REQUIRED
]);
echo "Bucket created successfully.";
} catch (Aws\S3\Exception\S3Exception $e) {
// output error message if fails
echo $e->getMessage();
}
Make sure to replace the placeholders with the actual values. This code creates a bucket on your S3 dashboard. We are going to upload a file under this bucket.
The next job is writing code for uploading files on the Amazon S3 bucket. For the sake of the tutorial, I am creating different PHP files and writing code in them. In your case, feel free to implement the logic depending on your project flow.
Upload File to Amazon S3 Bucket
You are ready with the bucket to store your files. Create a file upload-to-s3.php
and place the below code in this file.
upload-to-s3.php
<?php
require 'vendor/autoload.php';
use Aws\S3\S3Client;
// Instantiate an Amazon S3 client.
$s3Client = new S3Client([
'version' => 'latest',
'region' => 'YOUR_AWS_REGION',
'credentials' => [
'key' => 'ACCESS_KEY_ID',
'secret' => 'SECRET_ACCESS_KEY'
]
]);
$bucket = 'YOUR_BUCKET_NAME';
$file_Path = __DIR__ . '/my-image.png';
$key = basename($file_Path);
// Upload a publicly accessible file. The file size and type are determined by the SDK.
try {
$result = $s3Client->putObject([
'Bucket' => $bucket,
'Key' => $key,
'Body' => fopen($file_Path, 'r'),
'ACL' => 'public-read', // make file 'public'
]);
echo "Image uploaded successfully. Image path is: ". $result->get('ObjectURL');
} catch (Aws\S3\Exception\S3Exception $e) {
echo "There was an error uploading the file.\n";
echo $e->getMessage();
}
Here, you should assign the name of the bucket to $bucket
variable. In my case, I am uploading a file ‘my-image.png’ which path I set in the code. Accordingly, you should adjust the path of your files. Finally, I am printing the path of an uploaded file using get()
method on the response received.
I have also passed the key=>value pair as 'ACL' => 'public-read'
. This pair sets your file access to the public. If you wish to keep your storage private then remove this line from the code.
Now run the upload-to-s3.php
file on the browser and your file should be uploaded on the Amazon S3 bucket.
Using Amazon S3 Multipart Uploads
We used the method putObject
to upload our file. Using this method, you can upload objects up to 5 GB in size. And by using the multipart upload methods, you can upload objects from 5 MB to 5 TB in size.
But while working on the real-time application, we might not know which method should be used for the task – PutObject
or MultipartUploader
. The best option is to use ObjectUploader
. It uploads a large file to Amazon S3 using either PutObject
or MultipartUploader
, depending on what is best based on the payload size.
The code is as follows.
<?php
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
use Aws\S3\ObjectUploader;
use Aws\S3\MultipartUploader;
use Aws\Exception\MultipartUploadException;
// Instantiate an Amazon S3 client.
$s3Client = new S3Client([
'version' => 'latest',
'region' => 'YOUR_AWS_REGION',
'credentials' => [
'key' => 'ACCESS_KEY_ID',
'secret' => 'SECRET_ACCESS_KEY'
]
]);
$bucket = 'artisansweb';
$file_Path = __DIR__ . '/dummy-images.zip';
$key = basename($file_Path);
// Using stream instead of file path
$source = fopen($file_Path, 'rb');
$uploader = new ObjectUploader(
$s3Client,
$bucket,
$key,
$source,
'public-read',
);
do {
try {
$result = $uploader->upload();
if ($result["@metadata"]["statusCode"] == '200') {
print('<p>File successfully uploaded to ' . $result["ObjectURL"] . '.</p>');
}
} catch (MultipartUploadException $e) {
rewind($source);
$uploader = new MultipartUploader($s3Client, $source, [
'state' => $e->getState(),
'acl' => 'public-read',
]);
}
} while (!isset($result));
fclose($source);
Delete File from Amazon S3 Bucket
If you want to delete files(objects) from your S3 bucket, you need to use deleteObject
method along with bucket and file names. Refer to the code below.
<?php
require 'vendor/autoload.php';
use Aws\S3\S3Client;
$s3Client = new S3Client([
'version' => 'latest',
'region' => 'YOUR_AWS_REGION',
'credentials' => [
'key' => 'ACCESS_KEY_ID',
'secret' => 'SECRET_ACCESS_KEY'
]
]);
try {
$result = $s3Client->deleteObject([
'Bucket' => 'BUCKET_NAME',
'Key' => 'FILE_NAME',
]);
} catch (Aws\S3\Exception\S3Exception $e) {
// output error message if fails
echo $e->getMessage();
}
I hope you understand about creating a bucket and uploading files to Amazon S3. You may also want to check example codes provided by AWS on GitHub.
Related Articles
- Upload Files to Google Cloud Storage using PHP
- How to Upload File to S3 using Laravel Filesystem
- How to Upload Images to Another Server Through FTP in Laravel
If you liked this article, then please subscribe to our YouTube Channel for video tutorials.
I am trying to use this code. However, I am getting following error
Fatal error: Uncaught InvalidArgumentException: Missing required client configuration options: region: (string) A “region” configuration value is required for the “” service (e.g., “us-west-2”). A list of available public regions and endpoints can be found at http://docs.aws.amazon.com/general/latest/gr/rande.html. in C:\xampp\htdocs\assessment\vendor\aws\aws-sdk-php\src\ClientResolver.php:435 Stack trace: #0 C:\xampp\htdocs\assessment\vendor\aws\aws-sdk-php\src\ClientResolver.php(331): Aws\ClientResolver->throwRequired(Array) #1 C:\xampp\htdocs\assessment\vendor\aws\aws-sdk-php\src\AwsClient.php(199): Aws\ClientResolver->resolve(Array, Object(Aws\HandlerList)) #2 C:\xampp\htdocs\assessment\vendor\aws\aws-sdk-php\src\S3\S3Client.php(353): Aws\AwsClient->__construct(Array) #3 C:\xampp\htdocs\assessment\upload-to-s3.php(8): Aws\S3\S3Client->__construct(Array) #4 {main} thrown in C:\xampp\htdocs\assessment\vendor\aws\aws-sdk-php\src\ClientResolver.php on line 435
Can you please help me with this?
Did you pass the correct AWS region?
Yes, I made a very silly mistake It is working absolutely fine now.
Thankyou for the code and request too 😉
I am glad it worked for you.
How to implement it for an extra large file., We implemented but it does not work!!
What was the error? Is it related to maximum execution time exceeded? If so, you need to edit the PHP configuration file and increase the execution time.
Alternately, add the below line to the code which will removes the execution time limit.
set_time_limit(0);
Fantastic!! Fully working code. But not mentioned about bucket policy. Without appropriate bucket policy the code will not work.
This was a really helpful article. Has anyone heard about/tried Binfer Web Drop? The site is https://www.binfer.com/products/web-drop
Can you give me working example of bucket name dynamically through html form?