Upload file to AWS s3 bucket using PHP


Certainly! To upload a file to an AWS S3 bucket using PHP, you'll need to utilize the AWS SDK for PHP (specifically, the AWS S3 client). Before starting, ensure you have the AWS SDK for PHP installed via Composer.

Here's an example demonstrating how to upload a file to an AWS S3 bucket using PHP:

1. Install AWS SDK for PHP:

Install the AWS SDK for PHP using Composer:

composer require aws/aws-sdk-php

2. Code to Upload File to S3:

Here's the PHP code that uploads a file to an AWS S3 bucket:


require 'vendor/autoload.php'; // Include the Composer autoloader

use Aws\S3\S3Client;

use Aws\S3\Exception\S3Exception;

// AWS credentials

$bucketName = 'your_bucket_name';

$accessKeyId = 'your_access_key_id';

$secretAccessKey = 'your_secret_access_key';

// Region and version

$region = 'your_aws_region';

$version = 'latest';

// Create an S3Client

$s3 = new S3Client([

    'version' => $version,

    'region' => $region,

    'credentials' => [

        'key' => $accessKeyId,

        'secret' => $secretAccessKey,



// File to be uploaded

$filePath = '/path/to/your/file.ext'; // Replace with the path to your file

$key = 'folder/file.ext'; // Replace with the desired key in the S3 bucket

try {

    // Upload file to S3

    $result = $s3->putObject([

        'Bucket' => $bucketName,

        'Key' => $key,

        'SourceFile' => $filePath,

        'ACL' => 'public-read', // Set permissions as needed


    echo "File uploaded successfully to S3: " . $result['ObjectURL'];

} catch (S3Exception $e) {

    echo "Error uploading file: " . $e->getMessage();



Replace `'your_bucket_name'`, `'your_access_key_id'`, `'your_secret_access_key'`, `'your_aws_region'`, `'/path/to/your/file.ext'`, and `'folder/file.ext'` with your actual AWS S3 bucket details, file path, and desired S3 key for the uploaded file.

This code uses the `putObject` method of the AWS S3 client to upload a file to the specified bucket. Adjust the access control (`'ACL'`) as per your requirements. The `'public-read'` ACL makes the uploaded file publicly accessible.

Make sure that the AWS credentials provided have the necessary permissions to upload files to the specified S3 bucket.

Remember to handle any errors and add appropriate error-handling mechanisms in your application for production use.