Amazon S3 (Simple Storage Service) is the most popular cloud-based object storage service provided by Amazon Web Services (AWS).Amazon S3 is highly scalable,secure and durable data storage to store and retrieve data over the web.

Php AWS S3 - How to Use AWS S3 Bucket in PHP to Store and Manage Files

Table Of Content

1 Prerequisites

1.) PHP version of >7.4
2.) Composer
3.) AWS S3 Account

2 Introduction

Generally web applications stores, uploaded files in local web server.Alternatively you can store the files in any cloud storages, In this article, we're going to discuss how you can use Amazon S3 to store and manage files through PHP with the help of aws-sdk-php.

3 Create / Login into Amazon S3 Account

You need to create or Login into AWS account
After Sign into the account, In the top bar and Search for the S3 service and go to the S3 Management Console.

In S3 Management Console create a New Bucket to store files.

Get AWS Access Key ID and AWS Secret Access Key:
Search "IAM Console" and go to the IAM Console.

From the left navigation menu, select Users under the Access management section.
Create a user with AmazonS3FullAccess permission.

Once User Created Successfully, the Access Key ID and Secret Access Key will be generated.

4 Create Project Folder "aws-app"

Create Project Folder "aws-app" in root directory store all project files

5 Install AWS SDK for PHP 5

First, make sure your computer has a composer.
Use the following command to install PHP AWS SDK.

composer require aws/aws-sdk-php

6 Configure AWS Credentials in Config.php

In the config.php file, AWS configuration variables are defined.

<?php
define('AWS_ENDPOINT', 'xxxxxx');   
define('AWS_VERSION', 'latest');   
define('AWS_ACCESS_REGION', 'xxxxxx');   
define('AWS_BUCKET_NAME', 'xxxxxx'); 
define('AWS_ACCESS_KEY_ID', 'xxxxxx'); 
define('AWS_ACCESS_KEY_SECRET', 'xxxxxx'); 
?>

7 Create S3 Bucket (create.php)

In this section, we'll build the create.php file, which contains the code to create Bucket in S3 Storage.
Go ahead and create the create.php file with the following codes.

<?php
require 'vendor/autoload.php'; 
use Aws\S3\S3Client; 
include('config.php');

$s3 = new S3Client([ 
    'endpoint' => AWS_ENDPOINT,
    'version' => AWS_VERSION, 
    'region'  => AWS_ACCESS_REGION, 
    'credentials' => [ 
        'key'    => AWS_ACCESS_KEY_ID, 
        'secret' => AWS_ACCESS_KEY_SECRET, 
    ] 
]); 
    //Code to create a bucket
    $s3->createBucket(array('Bucket' => 'getsamplecode'));

?>

Firstly, we include the necessary dependencies. The config.php file contains all the AWS credentials.
The S3Client class is imported from the AWS SDK for PHP using the use statement.

Next, we have created a new s3 object for S3Client class, we are using "createBucket" method to create new bucket

8 Create Upload Form (upload_form.php)

In this section, we'll build the upload_form.php file, which contains HTML code which creates form with file input field and submit button.
Go ahead and create the upload_form.php file with the following contents.

<form method="post" action="store.php" enctype="multipart/form-data">
    <div class="form-group">
        <label><b>Select File:</b></label>
        <input type="file" name="s3file" class="form-control" required>
    </div>
    <div class="form-group">
        <input type="submit" class="btn btn-primary" name="submit" value="Upload">
    </div>
</form>

9 Storing Files to S3 (store.php)

In this section, we'll build the store.php file, which contains code to upload file to S3 Storage
Go ahead and create the store.php file with the following code.

<?php
require 'vendor/autoload.php'; 
use Aws\S3\S3Client; 
include('config.php');
   
if(isset($_POST["submit"])){ 

    // Check whether user inputs are empty 
    if(!empty($_FILES["s3file"]["name"])) { 

        //Uploaded File info 
        $file_name = basename($_FILES["s3file"]["name"]); 
        $file_temp = $_FILES["s3file"]["tmp_name"]; 
             
            if(is_uploaded_file($file_temp)){ 

                // Create s3 Object 
                $s3 = new S3Client([ 
                    'endpoint' => AWS_ENDPOINT,
                    'version' => AWS_VERSION, 
                    'region'  => AWS_ACCESS_REGION, 
                    'credentials' => [ 
                        'key'    => AWS_ACCESS_KEY_ID, 
                        'secret' => AWS_ACCESS_KEY_SECRET, 
                    ] 
                ]); 
 
                // Upload file to S3 bucket 
                try { 
                    $result = $s3->putObject([ 
                        'Bucket' => AWS_BUCKET_NAME, 
                        'Key'    => $file_name, 
                        'ACL'    => 'private', 
                        'SourceFile' => $file_temp 
                    ]); 
                    $result_arr = $result->toArray(); 
                     
                    if(!empty($result_arr['ObjectURL'])) { 
                        $message = "File was uploaded to the S3 bucket successfully!"; 
                    } else { 
                        $message = 'Upload Failed! S3 Object URL not found.'; 
                    } 
                } catch (Aws\S3\Exception\S3Exception $e) { 
                    $api_error = $e->getMessage(); 
                } 
                 
                
            }else{ 
                $message = "File upload failed!"; 
            } 
    }else{ 
        $message = 'Please select a file to upload.'; 
    } 
}
?>

10 Retrieving Files from S3 (list.php)

In this section, we'll build the list.php file, which contains the code to Retrieving Files from S3 Storage.
Go ahead and create the list.php file with the following contents.

<?php
require 'vendor/autoload.php'; 
use Aws\S3\S3Client; 
include('config.php');

 // Instantiate an Amazon S3 client 
 $s3 = new S3Client([ 
    'endpoint' => AWS_ENDPOINT,
    'version' => AWS_VERSION, 
    'region'  => AWS_ACCESS_REGION, 
    'credentials' => [ 
        'key'    => AWS_ACCESS_KEY_ID, 
        'secret' => AWS_ACCESS_KEY_SECRET, 
    ] 
]); 
$objects = $s3->getIterator('ListObjects', array(
    'Bucket' => AWS_BUCKET_NAME,
    'Prefix' => ''
));

<table border="1px" class="table">
  <thead>
  <tr>
    <th>Filename</th>
    <th>Download Link</th>
    <th>Delete</th>

  </tr>
</thead>
<tr>

<?php foreach ($objects as $object): ?>
<tr>
  <td>
  <?php echo $object['Key']; ?>
  </td>
  <td>
    <a href="<?php echo
      $s3->getObjectUrl('getsamplecode', $object['Key']); ?>" download="<?php
      echo $object['Key']; ?>" target="_blank">Download</a>
  </td>
  <td>
    <a  class="btn btn-danger btn-sm btn-wave-light md-btn-icon" href="delete.php?id=<?php echo $object['Key']; ?>" title="Delete" onclick="return confirm('Are you sure you want to delete this File?')">Delete</a>
  </td>
</tr>
<?php endforeach; ?>

?>

Create an Object for Classs S3Client() and pass require the configuration options (endpoint,version, region, credentials.key, and credentials.secret).
To Retrieving files from S3 bucket use the ListObjects() method of the S3Client

11 Folder Structure

12 Run Web Server to Test the App

Visit the URL http://localhost/aws-app/create.php

13 Conclusion

That’s all we need to do.
You can use this code in the web Applications to allow the user to upload files on Amazon Simple Storage Service (S3).

Tags