Implementation in PHP for uploading a file to AWS S3 (2024)

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 aPHP web developmentframework.

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:

1) 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

2) Create new library for AWS connection.

\app\LibrariesAwsUtility.php

3) 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

4) 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.

5) 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;

Recommended by LinkedIn

5 Tips To Scale Your Laravel Application For Better… Acquaint Softtech Private Limited 2 months ago
Laravel Scaling Approaches: A Comparative Study Acquaint Softtech Private Limited 1 month ago

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

//COPY SIGNED URL TO TEMP FOLDER

copy($effectiveUri_arr, $tempfile);

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

6) 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:

1)Install AWS S3 PHP SDK

composer require aws/aws-sdk-php

2)Create File Upload Form

3)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 experiencedSoftware development companyfor integrating PHP or Laravel code for uploading file using AWS S3.

Implementation in PHP for uploading a file to AWS S3 (2024)
Top Articles
Banken Lexikon - Christoph Heuermann - Weil dein Leben Dir gehört
25 Legit Ways to Make Money Online - DollarSprout
Dainty Rascal Io
Workday Latech Edu
1970 Chevelle Ss For Sale Craigslist
Usborne Links
Klustron 9
Why Is Stemtox So Expensive
Dc Gas Login
Enterprise Car Sales Jacksonville Used Cars
boohoo group plc Stock (BOO) - Quote London S.E.- MarketScreener
Costco Gas Foster City
Commodore Beach Club Live Cam
Gemita Alvarez Desnuda
Charter Spectrum Store
CANNABIS ONLINE DISPENSARY Promo Code — $100 Off 2024
Tyrone Unblocked Games Bitlife
Clare Briggs Guzman
Dulce
How to Make Ghee - How We Flourish
Vivaciousveteran
Www Pointclickcare Cna Login
Milwaukee Nickname Crossword Clue
Kabob-House-Spokane Photos
Catchvideo Chrome Extension
R/Airforcerecruits
Is Poke Healthy? Benefits, Risks, and Tips
Scott Surratt Salary
Cinema | Düsseldorfer Filmkunstkinos
Uncovering the Enigmatic Trish Stratus: From Net Worth to Personal Life
Package Store Open Near Me Open Now
Roadtoutopiasweepstakes.con
Jambus - Definition, Beispiele, Merkmale, Wirkung
Bee And Willow Bar Cart
Reli Stocktwits
Hisense Ht5021Kp Manual
Mistress Elizabeth Nyc
USB C 3HDMI Dock UCN3278 (12 in 1)
Craigslist Summersville West Virginia
Delaware judge sets Twitter, Elon Musk trial for October
Koninklijk Theater Tuschinski
Indio Mall Eye Doctor
Samantha Lyne Wikipedia
Oppenheimer Showtimes Near B&B Theatres Liberty Cinema 12
Torrid Rn Number Lookup
Makes A Successful Catch Maybe Crossword Clue
2487872771
Craigslist Pets Lewiston Idaho
Nkey rollover - Hitta bästa priset på Prisjakt
Selly Medaline
Guidance | GreenStar™ 3 2630 Display
Latest Posts
Article information

Author: Patricia Veum II

Last Updated:

Views: 5596

Rating: 4.3 / 5 (44 voted)

Reviews: 91% of readers found this page helpful

Author information

Name: Patricia Veum II

Birthday: 1994-12-16

Address: 2064 Little Summit, Goldieton, MS 97651-0862

Phone: +6873952696715

Job: Principal Officer

Hobby: Rafting, Cabaret, Candle making, Jigsaw puzzles, Inline skating, Magic, Graffiti

Introduction: My name is Patricia Veum II, I am a vast, combative, smiling, famous, inexpensive, zealous, sparkling person who loves writing and wants to share my knowledge and understanding with you.