Uploading files on Amazon AWS S3 server using PHP

|
| By Webner

Before uploading any document to Amazon AWS S3 server, make sure that user has to write access on the bucket where files will be saved else it will throw ‘Access denied’ error. Apart from the write permissions, access keys are also required in the code which we get while creating the user on S3 server. These keys are associated with the user and are applicable to all the buckets (i.e. folders) the user creates. These keys are:

1. Access Key Id
2. Secret Key Id

After getting these keys, files can be easily uploaded on S3 server.

Below is the sample code used to serve the purpose:

<?php
//create S3Client object with access keys
$client = new S3Client([
    'credentials' => [
        'key' => “<amazon s3 access key id>”,
     'secret' => “<amazon s3 secret key id>”,
     ],
    'region' => “<local region where the bucket is created. (E.g. eu-west)>”,
    'version' => 'latest', //if you don’t know the current version, just write ‘latest’
]);

$fileName = “<file name to be uploaded>”;

$changedFileName = str_replace(" ","",$fileName); //replace all spaces in filename if any with empty string, as S3 doesn’t allow files with spaces to be added as per naming conventions

$uploadedFileName = trim($changedFileName); //remove any whitespaces from filename

// Upload the file using putObject method of S3Client. The type and size of the file will be determined by the SDK.
try {
  $response = $client->putObject([
   'Bucket' => ‘<bucket-name where the file will be stored>’,
   'Key' => $uploadedFileName,
   'ACL' => 'public-read', //giving public access to the file
]);
print_r( $response ); //print the response coming from AWS

} catch (Aws\S3\Exception\S3Exception $e) {

   echo "An error occurred while uploading the file on server.";
}
?>

Leave a Reply

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