Implementation in PHP for uploading a file to AWS S3

The need to store users’ files is a necessary part of maintaining a software application. These user files can be anything such as images, videos, or PDFs. App creators usually save such files on the server. But, at a certain point in time, the amount of data becomes massive or there might be a need to store very large files. Such scenarios can be effectively handled using AWS S3, a dedicated file-uploading service. It’s a web-based Cloud storage service by Amazon. It comes with web service interfaces based on REST and SOAP. With S3, the task of file uploading becomes easier and quicker.
This post provides you with step-by-step guidance on how to upload files to AWS S3 in PHP. Here, we’ve considered how to upload file to AWS S3 in Laravel and PHP. Laravel is a PHP web development framework.
Before we dive deeper into the topic, let me provide you with some insights on certain crucial aspects you need to know before commencing the actual process of uploading your files to AWS S3.

Reasons to upload files to AWS S3

So, why is it a best practice to upload files to AWS? This approach is one of the most viable solutions to store data securely in the Cloud and manage this data effectively. Take a look at the reasons:

Unlimited Storage

The Cloud storage service AWS S3 supports mass data storage in Cloud-native apps and solutions. It allows infinite storage for data and objects. Different data types and formats are supported. So, users do not require to add more storage volumes to their already existing file storage infrastructure. You can store any file sized between 0 bytes and 5 gigabytes. AWS S3 stores data in the form of objects in S3 Buckets.

Reliability & Scalability

The Cloud storage service AWS S3 is reliable and scalable. You can store huge chunks of data and retrieve this data very easily. Also, with AWS S3, it becomes easy to download and upload huge files without having to worry about network bandwidth problems or storage limitations. Besides data storage, it also provides data backup and recovery options.

Laravel Integration

Laravel Integration is a boon as this robust framework supports AWS S3 integration by default. Laravel comes with multiple built-in features that are compatible with AWS S3. The storage façade is an example. Laravel integration simplifies the tasks of file downloading, file uploading, and file management in your application, with the help of a simple & consistent API.

Versioning

AWS S3 supports versioning. This means the different variants of an object or a file can stay within the same bucket. And, if you remove an object or a file by mistake, there’s the option for recovery or rollback. With AWS S3, you can also manage an object’s non-current version, if you have implemented the expiration lifecycle policy for that object.

High-grade Security

High-grade security is one of the most desirable offerings. AWS S3 offers built-in security features such as access control, strong encryption, etc. It comes with multiple certifications for security and regulatory compliances. This way, your data is protected against security vulnerabilities. Also, you can comply with the regulatory protocols mandated in your area without much ado. Files uploaded to AWS S3 are fully secure and least likely to face security issues like unauthorized access.

Cost-efficiency

AWS S3 is one of the most cost-efficient ways of file storage and file management. Here, the user requires to pay only for storing and transferring the data they use. It’s way less expensive than configuring and managing in-house storage infrastructure.

We can use following way to implement AWS S3 upload in Laravel:

    • Install following package-
composer require aws/aws-sdk-php-laravel “~3.0”
composer require league/flysystem-aws-S3-v3l “^1.0”
composer require league/flysystem-cached-adapter “~1.0
    • Create new library for AWS connection.

\app\LibrariesAwsUtility.php

    • ENV variables-

#Client info

AWS_ACCESS_KEY_ID=AKIAQQP246GMXXHSNV5I

AWS_SECRET_ACCESS_KEY=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

AWS_DEFAULT_REGION=us-west-2

AWS_BUCKET=dynafios-development-app-storage

END_POINT=https://dynafios-development-app-storage.S3.us-west-2.amazonaws.com

AWS_USE_PATH_STYLE_ENDPOINT=false

    • To upload report –

//For AWS File Upload-need to include

use App\Libraries\AwsUtility;

//Start S3 bucket url change aws – nvn

$storage_path_file_path=$report_path.’/’.$report_filename;

$awsObj_result = AwsUtility::awsUploadSubmit($storage_path_file_path);

$effectiveUri=$awsObj_result->getData()->effectiveUri;

//End S3 bucket url change aws – nvn

//To save URL path in DB-

$hospital_report->awsfilename = $effectiveUri;

a- We have created temp folder in

storage\temp

b- When report is generated the name is saved in the database and file is saved in temp folder. Now for uploading to AWS bucket we use temp path and after uploading we remove the temp path.
As per requirement.
  • For download, we use function from LibrariesAwsUtility.php and download on the fly temporary url that does not exist after download.

//S3 file download from bucket–nvn

$awsObj_result_down = awsUtility::awsDownloadTempUrl($filename);

$effectiveUri_arr = $awsObj_result_down->getData()->effectiveUri;

$onlyfilename = $awsObj_result_down->getData()->onlyfilename;

if ($effectiveUri_arr == “Failed”) {

//In case URL not saved or link break

$S3fileDownlaod = “Failed”;

return Redirect::back()->with([

//”error” => Lang::get(“hospital.S3_filenot_found_uploaded”),

“error” => “File Not Found!!”,

]);

//REDIRECT WITH MESSAGE

}

$filename = $onlyfilename;

$tempfile = tempnam(sys_get_temp_dir(), $filename);

//COPY SIGNED URL TO TEMP FOLDER

copy($effectiveUri_arr, $tempfile);

return response()->download($tempfile, $filename);

  • For delete we use function from LibrariesAwsUtility.php which delete file from aws but not from db. As per requirment.

// aws S3 file delete

$awsObj_result_del = awsUtility::awsDeleteFile($filename);

if (isset($awsObj_result_del)) {

// Log::Info(‘Deleted S3 File!HospitalController-getDeleteReport() ‘);

return Redirect::back()->with([

“success” => Lang::get(“hospitals.delete_report_success”),

]);

} else {

return Redirect::back()->with([

“error” => Lang::get(“hospital.delete_report_error”),

]);

}

return Redirect::back()->with([

“success” => Lang::get(“hospitals.delete_report_success”),

]);

Alternatively you can use Laravel’s File System as well, to upload file to AWS S3.

File can be uploaded to AWS S3 in Core PHP as below:

    • Install AWS S3 PHP SDK
composer require aws/aws-sdk-php
    • Create File Upload Form
    • upload-to-S3.php file

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’

]

]);

// Check whether file exists before uploading it

if(move_uploaded_file($_FILES[“anyfile”][“tmp_name”], “upload/” . $filename)){

$bucket = ‘YOUR_BUCKET_NAME’;

$file_Path = __DIR__ . ‘/upload/’. $filename;

$key = basename($file_Path);

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 file.\n”;

echo $e->getMessage();

}

echo “Your file was uploaded successfully.”;

}else{

echo “File is not uploaded”;

}

In Conclusion

I hope you are now well-versed in uploading a file to AWS S3 using PHP or Laravel. However, if you lack the necessary technical expertise, you can seek professional help from an experienced Software development company for integrating PHP or Laravel code for uploading file using AWS S3.
Share Post