Why Use Amazon S3 for File Storage in PHP Applications?

Amazon S3 is the leading choice for PHP developers in 2026 handling user uploads, media, backups, or app assets. Local server storage quickly becomes a bottleneck as apps grow — here’s why S3 wins over traditional disks:

  • Unlimited Scalability — Store petabytes without provisioning hardware; auto-scales effortlessly during traffic spikes.
  • Extreme Durability & Availability — 99.999999999% (11 9s) durability with multi-AZ replication — far safer than local RAID setups.
  • Cost-Effective Pay-as-You-Go — No upfront costs; cheap storage + Intelligent-Tiering saves money on infrequently accessed files.
  • Offload Your PHP Server — Uploads/downloads happen directly to/from S3 (or via CloudFront CDN), reducing CPU, I/O, and bandwidth load on your web servers for faster performance and easier scaling.
  • Strong Security Built-In — Default private buckets, SSE encryption, IAM policies, presigned URLs, and compliance (GDPR, HIPAA) — simpler and more secure than hardening your own server.
  • Seamless PHP Integration — Official AWS SDK for PHP (v3+) + Laravel/Symfony support makes uploads, listing, and management straightforward.

In short: For any PHP app beyond prototypes, S3 delivers reliability, speed, security, and savings — letting you focus on code, not infrastructure.



How to Use AWS S3 Bucket in PHP: Complete Step-by-Step Tutorial

Table Of Content

1 Prerequisites

  • PHP 8.1+
  • Composer installed
  • An AWS account with S3 access
  • IAM user with programmatic access (AmazonS3FullAccess policy — use least privilege in production)

2 Introduction

Amazon Simple Storage Service (S3) is a scalable, secure object storage service ideal for storing and serving files in PHP applications. In this updated 2026 guide, you'll learn to integrate AWS S3 using the official AWS SDK for PHP (v3+), including secure credential handling, file uploads, listing, and deletion.

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-s3-php"

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

5 Install AWS SDK for PHP

run inside project folder (e.g., aws-s3-php) :

composer require aws/aws-sdk-php

6 Setting Up AWS Credentials Securely

Avoid hardcoding keys. Use the shared credentials file (~/.aws/credentials) or environment variables. Example credentials file:


[default]
aws_access_key_id = YOUR_ACCESS_KEY
aws_secret_access_key = YOUR_SECRET_KEY

Or use IAM roles on EC2/Lambda for zero-key management.

7 Create an S3 Bucket Programmatically

Create create-bucket.php:


<?php
require 'vendor/autoload.php';

use Aws\S3\S3Client;
use Aws\Exception\AwsException;

$s3Client = new S3Client([
    'region'  => 'us-east-1',  // Change to your region
    'version' => 'latest'
]);

$bucketName = 'your-unique-bucket-name-' . time();  // Must be globally unique

try {
    $result = $s3Client->createBucket([
        'Bucket' => $bucketName,
    ]);
    echo "Bucket created successfully: " . $result['Location'] . "\n";
} catch (AwsException $e) {
    echo "Error: " . $e->getAwsErrorMessage() . "\n";
}
?>

8 Create Upload Form (upload-form.html)

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

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>Upload File to AWS S3</title>
</head>
<body>
    <h1>Upload File to S3</h1>
    <form action="upload.php" method="post" enctype="multipart/form-data">
        <label for="file">Select File:</label>
        <input type="file" id="file" name="file" required>
        <button type="submit">Upload to S3</button>
    </form>
</body>
</html>

9 Storing Files to S3 (upload.php)

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

<?php
require 'vendor/autoload.php';

use Aws\S3\S3Client;
use Aws\Exception\AwsException;

// Initialize S3 client
$s3Client = new S3Client([
    'region'  => 'us-east-1',
    'version' => 'latest'
]);

$bucket = 'your-bucket-name';  // Replace with your bucket

if (isset($_FILES['file']) && $_FILES['file']['error'] === UPLOAD_ERR_OK) {
    $file = $_FILES['file'];
    $key = basename($file['name']);

    try {
        $result = $s3Client->putObject([
            'Bucket'     => $bucket,
            'Key'        => $key,
            'SourceFile' => $file['tmp_name'],
            'ACL'        => 'private',  // Change to 'public-read' if needed
            'ContentType' => mime_content_type($file['tmp_name']),
        ]);
        echo "File uploaded successfully. ETag: " . $result['ETag'] . "<br>";
        echo "Object URL: " . $result['ObjectURL'] . "<br>";
        echo "<a href='list.php'>View Files</a>";
    } catch (AwsException $e) {
        echo "Upload failed: " . $e->getAwsErrorMessage();
    } catch (Exception $e) {
        echo "General error: " . $e->getMessage();
    }
} else {
    echo "No file uploaded or upload error.";
}
?>

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;
use Aws\Exception\AwsException;

// Initialize S3 client
$s3Client = new S3Client([
    'region'  => 'us-east-1',
    'version' => 'latest'
]);

$bucket = 'your-bucket-name';

try {
    $objects = $s3Client->listObjectsV2([
        'Bucket' => $bucket
    ]);

    echo "<h1>Files in Bucket: $bucket</h1>";
    echo "<ul>";
    foreach ($objects['Contents'] ?? [] as $obj) {
        $key = $obj['Key'];
        
        // Generate presigned URL for download (expires in 20 minutes)
        $cmd = $s3Client->getCommand('GetObject', [
            'Bucket' => $bucket,
            'Key'    => $key
        ]);
        $request = $s3Client->createPresignedRequest($cmd, '+20 minutes');
        $presignedUrl = (string) $request->getUri();

        echo "<li>";
        echo "$key (Size: " . $obj['Size'] . " bytes) - ";
        echo "<a href='$presignedUrl' target='_blank'>Download (expires in 20 min)</a> - ";
        echo "<a href='delete.php?key=" . urlencode($key) . "'>Delete</a>";
        echo "</li>";
    }
    echo "</ul>";
    echo "<a href='upload-form.html'>Upload More Files</a>";
} catch (AwsException $e) {
    echo "Error listing objects: " . $e->getAwsErrorMessage();
}
?>

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 Delete File from S3 (delete.php)


<?php
require 'vendor/autoload.php';

use Aws\S3\S3Client;
use Aws\Exception\AwsException;

// Initialize S3 client
$s3Client = new S3Client([
    'region'  => 'us-east-1',
    'version' => 'latest'
]);

$bucket = 'your-bucket-name';
$key = $_GET['key'] ?? '';

if ($key) {
    try {
        $s3Client->deleteObject([
            'Bucket' => $bucket,
            'Key'    => $key
        ]);
        echo "File '$key' deleted successfully.
"; echo "<a href='list.php'>Back to File List</a>"; } catch (AwsException $e) { echo "Error deleting file: " . $e->getAwsErrorMessage(); } } else { echo "No file key provided."; } ?>

12 Folder Structure


aws-s3-php/
├── composer.json
├── create-bucket.php
├── upload-form.html
├── upload.php
├── list.php
├── delete.php
└── .env  (optional for bucket name)

13 Running the Demo

  • Run php create-bucket.php from CLI to create a bucket (optional; you can create manually in AWS console).
  • Open http://localhost:8000/upload-form.html in browser.
  • Upload a file → Redirects to success message.
  • Go to http://localhost:8000/list.php to see files, download via presigned URLs, or delete.
  • For large files, add multipart upload logic as mentioned in best practices.

14 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).
Revathi M - PHP and CodeIgniter Developer

Written by Revathi M

PHP Developer & Technical Writer · 10+ years building web applications with CodeIgniter and Laravel

Revathi specializes in PHP backend development, authentication systems, and REST API design. She writes practical, production-tested tutorials at Get Sample Code to help developers build secure applications faster.

Frequently Asked Questions

You need PHP version greater than 7.4, Composer installed, and an AWS account with S3 access.

Log into AWS Console, go to S3 > Create bucket. Then in IAM > Users > Create user, attach `AmazonS3FullAccess` policy, and generate Access Key ID and Secret Access Key.

Run `composer require aws/aws-sdk-php` to install the official AWS SDK for PHP.

Create a `config.php` file and define constants like `AWS_ACCESS_KEY_ID`, `AWS_ACCESS_KEY_SECRET`, `AWS_ACCESS_REGION`, `AWS_BUCKET_NAME`, `AWS_VERSION` ('latest'), and optionally `AWS_ENDPOINT`.

Initialize `S3Client`, then use `$s3->createBucket(['Bucket' => 'your-bucket-name']);` in a script like `create.php`.

Use a simple HTML form in `upload_form.php` with enctype=`multipart/form-data`, a file input named `s3file`, and submit to `store.php`.

In `store.php`, check if file is uploaded with `is_uploaded_file()`, initialize `S3Client`, then use `putObject()` with `Bucket`, `Key` (filename), `SourceFile` (temp path), and `ACL` => 'private'.

Use `$s3->getIterator('ListObjects', ['Bucket' => AWS_BUCKET_NAME])` to fetch objects, then loop and display in a table with filename, download link, and delete option.

Use `$s3->getObjectUrl($bucket, $key)` to get the object URL, which works for private files with proper credentials.

Common causes: invalid credentials, wrong region/bucket, file not selected, or temp file issues. Check for `S3Exception` messages in the try-catch block.

Change 'ACL' => 'private' to 'ACL' => 'public-read' in the `putObject()` call during upload.

Verify Access Key ID, Secret, Region, and Bucket Name in `config.php`. Ensure the IAM user has `AmazonS3FullAccess` or specific permissions like s3:PutObject, s3:ListBucket.

Though not shown in the tutorial, use `$s3->deleteObject(['Bucket' => $bucket, 'Key' => $filename]);` in a `delete.php` script.

Place files in a web server directory (e.g., `aws-app/`), run Composer install, visit `http://localhost/aws-app/create.php` to create the bucket, then use the upload form and list page.