PHP How To Upload Folder and Files To AWS S3 Bucket

Reading Time: 7 minutes
3,518 Views

Inside this article we will see i.e PHP how to upload folder and files to AWS s3 bucket. There are very few simple steps by which we can upload files and folders into AWS s3 bucket.

AWS provides a composer package for PHP application. By the help of this package we can easily communicate with AWS s3 bucket with few keys and their APIs.

This article will give you the classified information about uploading files, folders and subfolders into S3 bucket in PHP. If you are wondering to find the solution about uploading files and folders, then this article will help you a lot with AWS S3 bucket.

Learn More –

Let’s get started.

Install AWS PHP SDK

Before installation installation, please make sure these –

  • System should have composer installed
  • Project should have composer.json file

How To generate composer.json file

To generate a composer.json file. Open project into terminal and run this command.

$ composer init

You can provide either the information to generate else you can simply press Enter to pick default value.

So, here we have generate composer.json file with all default values in it.

Next,

Install AWS SDK.

$ composer require aws/aws-sdk-php

You will see like this –

It will create a vendor folder into your project folder.

Next,

Create Application To Upload Folder & Files

Create a file with any name like upload-project.php.

You need these while working with AWS S3 bucket to upload any files or folders.

  • AWS Access Key
  • AWS Secret Key
  • Bucket Name

Step #1 – AWS S3 Connection

// Instantiate an Amazon S3 client.
$s3Client = new S3Client([
    'version' => 'latest',
    'region'  => 'us-east-1', // Your AWS region
    'credentials' => [
        'key'    => $awsAccessKey,
        'secret' => $awsSecretKey
    ]
]);

Step #2 – Upload File To Bucket

$result = $s3Client->putObject([
    'Bucket' => $bucket,
    'Key'    => $file_Path,
    'Body'   => fopen($file_Path, 'r'),
    'ACL'    => 'public-read',
]);

Open upload-project.php file and write this complete code into it.

<?php

require 'vendor/autoload.php';

use Aws\S3\S3Client;

// List all files and folders in a main folder
function listFolderFiles($dir)
{
    $fileInfo     = scandir($dir);
    $allFileLists = [];

    foreach ($fileInfo as $folder) {
        if ($folder !== '.' && $folder !== '..') {
            if (is_dir($dir . DIRECTORY_SEPARATOR . $folder) === true) {
                $allFileLists[] = listFolderFiles($dir . DIRECTORY_SEPARATOR . $folder);
            } else {
                $allFileLists[] = $dir . "/" . $folder;
            }
        }
    }

    return $allFileLists;
}

// Upload a complete folder to AWS
function uploadFolderToAWS($dirLists)
{
    foreach ($dirLists as $dir) {

        if ($dir !== '.' && $dir !== '..') {
            if (is_array($dir) === true) {
                // Array
                uploadFolderToAWS($dir);
            } else {
                // file
                uploadFileToS3Bucket($dir);
            }
        }
    }
}

// Upload file to AWS S3
function uploadFileToS3Bucket($file_Path)
{
    $awsAccessKey = 'XXXX';
    $awsSecretKey = 'YYYYYYYYYY';
    $bucket = 'your-bucket-name';

    try {
        // Instantiate an Amazon S3 client.
        $s3Client = new S3Client([
            'version' => 'latest',
            'region'  => 'us-east-1', // Your AWS region
            'credentials' => [
                'key'    => $awsAccessKey,
                'secret' => $awsSecretKey
            ]
        ]);

        $result = $s3Client->putObject([
            'Bucket' => $bucket,
            'Key'    => $file_Path,
            'Body'   => fopen($file_Path, 'r'),
            'ACL'    => 'public-read',
        ]);
        echo "<pre>";
        print_r($result);
    } catch (Aws\S3\Exception\S3Exception $e) {
        echo "There was an error uploading the file.\n";
        echo $e->getMessage();
    }
}


$folderToMove = "your-project-folder";

$dirLists = listFolderFiles($folderToMove);

// Upload a complete site
uploadFolderToAWS($dirLists);

Inside above code, you can see it contains 3 functions.

  • listFolderFiles() – This function will list all files and folders from given directory
  • uploadFolderToAWS() – This function will send a single file to upload to AWS and also if the given directory contains subfolders then it will scan that also.
  • uploadFileToS3Bucket() – This function will upload file to AWS S3 bucket.

For this example, suppose $folderToMove = “your-project-folder”; contains subfolders and files.

$dirLists = listFolderFiles($folderToMove); This will list all files and folders inside it.

We are uploading each folder and files from above code to this uploadFolderToAWS($dirLists);

Then step by step above function will scan in two cases – First if it is a folder then same process will execute and again it scans the subfolder. In the second case if it is a file then directly it will upload file to AWS S3 bucket.

We hope this article helped you to learn about PHP How To Upload Folder and Files To AWS S3 Bucket Tutorial in a very detailed way.

Online Web Tutor invites you to try Skillshike! Learn CakePHP, Laravel, CodeIgniter, Node Js, MySQL, Authentication, RESTful Web Services, etc into a depth level. Master the Coding Skills to Become an Expert in PHP Web Development. So, Search your favourite course and enroll now.

If you liked this article, then please subscribe to our YouTube Channel for PHP & it’s framework, WordPress, Node Js video tutorials. You can also find us on Twitter and Facebook.

Sanjay KumarHello friends, I am Sanjay Kumar a Web Developer by profession. Additionally I'm also a Blogger, Youtuber by Passion. I founded Online Web Tutor and Skillshike platforms. By using these platforms I am sharing the valuable knowledge of Programming, Tips and Tricks, Programming Standards and more what I have with you all. Read more