AWS S3 guide with PHP Integration
Create a simple CRUD(Create, Read, Update, Delete) application using AWS S3 and PHP
What is Cloud Storage?
Cloud storage or Web storage is a web service where your data can be stored, accessed by its users.
Cloud storage is offered in two models:
- Pay only for what you use
- Pay on a periodic or monthly basis
Worldwide market shares of leading cloud infrastructure service providers in Q4- 2021:
Now, Let’s deep dive into Cloud Storage.
AWS Buckets and Objects
- A bucket is used to store objects. When data is added to a bucket, Amazon S3 creates a unique version ID and allocates it to the object.
- An object consists of data, key(assigned name) and metadata.
3. Set permissions
Manage public permissions — Do not grant public read access to this bucket
Manage system permissions — Do not grant Amazon S3 Log Delivery group write accessto this bucket
Select the created bucket:
Select a file to be added
Let’s now look how we can automate this process by creating a simple in-depth AWS S3 with PHP integration guide.
Before we continue to next step let’s look of some the Prerequisites:
● Active AWS Account.
● Web server solution software stack like WAMP, LAMP, XAMPP (version 7.4.2 or latest), MAMP according to your Operating system.
● PHP (version 7.3 or latest)
(For this tutorial, we’ll use the XAMPP(v7.4.2) server, which is a cross-platform software bundle that includes Apache, MariaDB, PHP, and Pearl, which is used to run PHP (v7.3) scripts)
Step 1:
First step first is you need ACCESS KEY and SECRET ACCESS KEY for performing all S3 related operations with PHP SDK (used during CRUD operation).
NOTE: Use an access key ID and secret access key to authenticate an Amazon Web Services (AWS) account in a Cloud Storage migration project. An AWS secret access key can’t be retrieved after it has been created. Once lost, it cannot be recovered; a new access key must be created.
Follow the steps below to create a new secret access key for an AWS account:
1. Sign into the AWS Management Console and open the IAM console.
2. In the navigation pane, choose Users.
3. Add a checkmark next to the name of the desired user, and then choose User Actions from the top.
Note: The selected user must have read and write access to the AWS S3 bucket for the migration.
Click on Manage Access Keys:
Note: Each AWS account can only have two access keys. If the secret access keys are lost, one of the existing access keys must be deleted, and a new one created.
Manage Access Keys:
1) Click on Show User Security Credentials.
2) Copy and paste the Access Key ID and Secret Access Key values or click on download credentials to download the credentials in a CSV (file).
Step 2:
Installing the AWS SDK for PHP Version 3:
You can install the AWS SDK for PHP Version 3 by following ways:
1) As a dependency via Composer:
First thing you need to install Composer (Package manager for PHP) from this official website https://getcomposer.org/
Visit to your project folder and then open command prompt and type command:
composer require aws/aws-sdk-php
And now add autoloader to your PHP scripts to utilize the AWS SDK for PHP in your scripts, include the autoloader in your scripts as follows.
<?php require '/path/to/vendor/autoload.php'; ?>
2) Installing by Using the ZIP file:
The AWS SDK for PHP includes a ZIP file containing all the classes and dependencies you need to run the SDK.
To install the SDK download the .zip file by clicking below link:
https://docs.aws.amazon.com/aws-sdk-php/v3/download/aws.zip, and then extract it into your project at a location you choose. Then include the autoloader in your scripts, as follows:
<?php require '/path/to/aws-autoloader.php'; ?>
Create connection.php file for your database connection related script and put below code:
<?php
$connection = mysqli_connect(“-host-name-“, “-databse username-”, “-database password-”,
“-databse name-”);
if(!$connection){
die("Error in connection to database ".mysqli_error($connection));
}
?>
now go to your index.php
Creating a client:
Write the below code to your file write as dependencies and initializer code:
<?php
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
//Create a S3Client
$s3 = new S3Client([
'profile' => 'default',
'version' => 'latest',
'region' => 'put your desired global server region',
'bucket' => 'put your created bucket name',
/* Below I provide hard coded credentials(not recommended), see best practice for providing
credentials to your application
https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_cred
entials_hardcoded.html */
'credentials' => [
'key' => 'put your access key id',
'secret' => 'put your secret access key'
],
]);
?>
Way to provide credential:
- Use credentials from environment variables.
Setting environment variables is useful if you’re doing development work on your local machine. Using environment variables to contain your credentials prevents you from accidentally sharing your AWS secret access key.
AWS documentation recommend that you never add your AWS access keys directly to the client in any production files. Many developers have had their account compromised by leaked keys. To set environment variable in windows operating system:
Visit to C:// drive => Users => choose your root user => create .aws folder => inside create file name credentials (for this you need to use Bracket or any code editor for creating file)
After creating file edit it and write below lines
[default] aws_access_key_id = PUT_YOUR_AWS_S3_ACCESS_KEY
aws_secret_access_key = PUT_YOUR_AWS_S3_SECRET_ACCESS_KEY
[Default] => Profile name of AWS S3, you can create multiple profiles as different profiles for different users.
- Upload file to AWS S3 Bucket form (include this code in index.php file
after the above code)
- For uploading a file putObject( ) method is used.
<html>
<head>
<title>Upload Data</title>
</head>
<body>
<h3>Upload the files</h3>
<form name="upload" action="upload.php" method="post" enctype="multipart/form-data">
<input type="file" name="uploaduser" id="uploaduser" />
<input type="submit" name="submit" value="upload"/>
</form>
</body>
</html>
for processing form of uploaded file create upload.php file and copy and paste below code:
<?php
if(isset($_FILES['uploaduser'])){
$files = $_FILES['uploaduser'];
$name = $files['name'];
$tmpName = $files['tmp_name'];
$size = $files['size'];
$extension = explode('.', $files['name']);
$extension = strtolower(end($extension));
$key = md5(uniqid());
$tmp_file_name = "{$key}.{$extension}";
$tmp_file_path= "files/{$tmp_file_name}";
move_uploaded_file($tmpName, $tmp_file_path);
try{
$s3->putObject([
'Bucket' => 'put your created bucket name',
'Key' => "uploads/{$name}",
]);
//remove the file from local folder unlink($tmp_file_path);
}
catch (AwsS3ExceptionS3Exception $ex){
die("Error uploading the file to S3");
}
header("Location: index.php");
exit();
}
?>
try{
$s3->putObject([
‘Bucket’ => ‘put your created bucket name’,
‘Key’ => “uploads/{$name}”
]); }‘Bucket’ => ‘put your created bucket name’,
=> AWS S3 bucket name that you want to use as a source for uploading your file.
‘Key’ => “uploads/{$name}”
=> upload is the folder name created inside the AWS S3 bucket after you upload your file.
List all uploaded files from AWS S3 bucket:
<table border="1px">
<thead>
<tr>
<th>Filename</th>
</tr>
</thead>
<tr>
<?php foreach ($result['Contents'] as $object): ?>
<tr>
<td>
<?php echo $object['Key']; ?>
</td>
</tr>
<?php endforeach; ?>
</table>
Get download link of content inside AWS S3 bucket:
<table border="1px">
<thead>
<tr>
<th>Filename</th>
</tr>
</thead>
<tr>
<?php foreach ($result['Contents'] as $object): ?>
<tr>
<td>
<a href="<?php echo
$s3->getObjectUrl('put-your-s3-bucket-name', $object['Key']); ?>" download="<?php
echo $object['Key']; ?>">Download</a>
</td>
</tr>
<?php endforeach; ?>
</table>
Delete content of AWS S3 bucket:
<?php
require('config.php');
$bucket = 'put-your-source-bucket-name'; //bucket name that contains your files/content
$folder ='aws-s3-folder-name-inside-your-file-store';
//for example myfolder/
$keyname = 'file-name';
//like if your file name is flower.jpg then put this name in the place of keyname(that means the path of flower.jpg file is myfolder/flower.jpg)
$result = $s3->deleteObject([
'Bucket' => $bucket,
'Key' => $folder."/". $keyname
]);
?>
Final application screenshots:
I hope you’ve enjoyed this PHP based AWS S3 tutorial. Now that we’ve utilised the AWS PHP SDK for S3, we’ll be able to use the SDK to continue designing applications that use AWS services directly through code.
This is a huge benefit for individuals interested in leveraging AWS services to build applications. In this article, we used the AWS PHP SDK to create buckets, manage user access keys, set up environment variables, upload data, list data from buckets, and then delete buckets/objects using PHP code and the AWS SDK.