Implementation in PHP for uploading a file to AWS S3

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.

The Complete Guide to Charts and How They Help Marketers and Businesses to Get Growth

The Complete Guide to Charts and How They Help Marketers and Businesses to Get Growth
Charts are a visual representation of data. You can use charts to display information quickly and easily. Charts integrate text with graphics or symbols to indicate the relationship between several data sets. Take a look at these examples. You can use a bar chart for indicating the sales pattern of a product over a certain timeline say a few years. The length of a bar in the chart signifies the product sales for a specific year.
Charts are a great way to convey complex information and compare several data sets. This is because pictorial representation is often a more powerful tool to display information. Research has proven the fact that it’s easier to understand and remember data represented visually via charts over plain textual data. This way, viewers can grasp the insights faster and more effortlessly. Google Charts is also an effective tool for data analysis and identifying trends, patterns, and outliers. This is the most popular form of chart leveraged by modern-day entrepreneurs. Businesses are using these charts as a productive way of data visualization on their websites or web/mobile apps. The Google chart gallery comes with a huge variety of ready-made charts starting from simple line-based charts to complicated ones like hierarchical tree maps.

What do you need to know about Google charts?

Google-based charts are web-based solutions that help software development teams visualize their website data in the form of histograms, pictographs, etc. These charts are Cloud-based and allow software development teams to create various types of interactive graphs and charts for displaying crucial data on their websites.
Google’s visualization API powers the charts, So, web app development teams can effortlessly integrate these carts into web apps. Anyone having a Google account can access
The charts are exposed as JavaScript classes and rendered with the help of SVG/HTML5 technology. This provides cross-platform portability to Android & iOS devices and cross-browser compatibility including VML for old IE versions. Entrepreneurs can even feed data into charts and create chart-related objects with the help of a selected ID. Users can refer to the Google Charts Documentation to seek assistance and resolve other queries.

Why is it important to use Google charts?

  • It is free to use and comes with a user-friendly interface.
  • It is an easy way to make a data visualization for your blog post or website.
  • You can use it to display data in a variety of formats, from bar graphs to pie charts.
  • Data visualization is the process of converting information into a graphical format that can be quickly comprehended and shared with others.

Features of Google-based charts?

  • Content Management
  • Custom Dashboards
  • Compatibility with different browsers and mobile platforms.
  • Multitouch Support
  • Lightweight
  • Simple Configurations
  • Visual Discovery
  • Multiple axes
  • Configurable tooltips
  • Date Time support.
  • Dataset Management
  • Print using a web page
  • External data from a server

What are some benefits of using Google-created charts?

  • Easily create charts with built-in templates.
  • A large library of chart types to choose from.
  • Flexible chart options to change colors, fonts, etc.
  • Simple tools to animate data in a chart or make changes to it over time.
However, in order to reap the benefits of this JavaScript-based data visualization library to the fullest and achieve your goal, it’s important to select the right kind of chart. There are a wide variety of Google-provided charts. Each type of chart serves a specific purpose. You need to identify your objective and then select the chart type that best fits your requirement.

TYPES OF GOOGLE CHART

How Easy They Are!

Google’s Charts are important because they allow data visualization in the browser with no need to download and install a plug-in.
The Google Chart API is a JavaScript library that lets users create graphs, charts, and maps in the browser without having to download or install a plug-in. With this API, developers can create interactive visualizations for websites and applications.

Some of the Visual EXAMPLES of the charts generated through google’s charts:

 
In the below Charts, we have merged the dataset to showcase the different formats. The Colored Labels Consists of Their Types:

How to integrate Google chart Pie

<!DOCTYPE html>

<html>

<script type=”text/javascript” src=”https://www.gstatic.com/charts/loader.js”></script>

<body>

<div>

id=”myChart” style=”width:100%; max-width:600px; height:500px;”>

</div>

<script>

google.charts.load(‘current’, {‘packages’:[‘corechart’]});

google.charts.setOnLoadCallback(drawChart);

function drawChart() {

var data = google.visualization.arrayToDataTable([

[‘Contry’, ‘Mhl’],

[‘Italy’,54.8],

[‘France’,48.6],

[‘Spain’,44.4],

[‘USA’,23.9],

[‘Argentina’,14.5]

]);

var options = {

title:’World Wide Wine Production’

};

var chart = new google.visualization.PieChart(document.getElementById(‘myChart’));

chart.draw(data, options);

}

</script>

</body>

</html>

Challenges Faced While Integration

1. Displaying real-time data without reloading the page.
Solution: – By using jQuery.
2. User interface customization in accordance with the client’s requirements.
 Solution: – By using bootstrap and with the help of jQuery.
3. Customizing the filters and labels that appear on the charts.
Solution: – With the help of HTML, CSS, and jQuery.
4. Retrieve the necessary data from the backend to present the results.
Solution: – Write an API in Laravel (PHP) to get the data and prepare by using jQuery to Display the google chart.

In Conclusion

Data visualization with Google-provided Charts can work wonders in your web development process. And, the good news is that the charts are continuously being updated with new features and enhancements to stay relevant as per the changing trends and offer advanced functionalities to users.
However, you must take care that your chart is captivating enough to make your point more convincing and add credibility to the presentation. Also, follow the best practices while you implement these charts. You may consider hiring professional Google chart developers if your requirements are complex and you lack the necessary expertise.