Skip to content

Instantly share code, notes, and snippets.

@CedricL46
Last active August 5, 2019 12:46
Show Gist options
  • Star 0 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save CedricL46/9f234212402916fd8e65323b7efb34e9 to your computer and use it in GitHub Desktop.
Save CedricL46/9f234212402916fd8e65323b7efb34e9 to your computer and use it in GitHub Desktop.
<?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
));
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment