How to upload a folder content to AWS S3 in PHP?

From machine learning to a lambda function, most of the projects running on AWS relies on an S3 bucket to store the files you need for other AWS services.

Uploading using the AWS S3 bucket web interface can be impossible when the folder contents contain thousands of files. (or if this folder is only available on an Apache server running PHP)

Running a small PHP script is then a great way to simplify the process. You’ll just need the following prerequisites :

Once this is done, you’ll need to adapt the following PHP script for your use case and0/d run it with :

php -f YOUR_SCRIPT_FILE_NAME.php

<?php
// Include AWS php sdk that you can download here : https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/getting-started_installation.html
require 'aws/aws-autoloader.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
// Initialize your S3 connection.
// To generate your YOUR_IAM_USER_KEY and YOUR_IAM_USER_SECRET create and Aws IAM user with the S3FullAccess Role
// to do so follow : https://docs.aws.amazon.com/IAM/latest/UserGuide/id_users_create.html
$s3 = new Aws\S3\S3Client([
'region' => 'YOUR_S3_REGION',
'version' => 'latest',
'credentials' => [
'key' => "YOUR_IAM_USER_KEY",
'secret' => "YOUR_IAM_USER_SECRET",
]
]);
$dir = "/FULL_DIRECTORY_TO_UPLOAD_PATH/*";
//for example $dir = "/home/ubuntu/Projets/MY_PROJECT/MY_FOLDER_TO_UPLOAD/*";
//For each file in your directory run the putObject S3 Api function
foreach (glob($dir) as $file) {
$file_name = str_replace('/FULL_DIRECTORY_TO_UPLOAD_PATH/', '', $file);
echo "Upload File Key : ".$file_name . "\n";
echo "Upload File Path : ".$file. "\n \n";
$result = $s3->putObject([
'Bucket' => 'YOUR_S3_BUCKET_NAME',
'Key' => 'FOLDER_NAME_INSIDE_S3_BUCKET/'.$file_name,
'Body' => fopen($file, 'r+')
]);
// Wait for the file to be uploaded and accessible :
$s3->waitUntil('ObjectExists', array(
'Bucket' => 'YOUR_S3_BUCKET_NAME',
'Key' => 'FOLDER_NAME_INSIDE_S3_BUCKET/'.$file_name
));
}

Leave a Comment

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.