Last active
August 5, 2019 12:46
-
-
Save CedricL46/9f234212402916fd8e65323b7efb34e9 to your computer and use it in GitHub Desktop.
Read full tutorial here : https://cedricleruth.com/how-to-upload-a-folder-contents-to-aws-s3-in-php/
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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