Upload File to AWS S3 Bucket In PHP

Upload File to AWS S3 Bucket In PHP

PHP upload file to amazon aws s3 bucket; This tutorial will show you how to upload file/image aws s3 bucket in PHP using aws-s3 PHP SDK.

Aws PHP SDK upload file to s3 bucket tutorial will provide you complete guide on how to create aws s3 bucket account and how to upload file/image to amazon aws s3 bucket using PHP aws s3 SDK.

How to Upload Files to Amazon AWS s3 Bucket using PHP

  • Step 1 – Create AWS S3 Bucket Account
  • Step 2 – Create PHP App
  • Step 3 – Install AWS S3 PHP SDK
  • Step 4 – Create File Upload Form
  • Step 5 – Create upload-to-s3.php file

Step 1 – Create AWS S3 Bucket Account

First of all, you need to create aws s3 bucket account by following the below given steps:

Setup amazon aws s3 bucket account; so you need to create account on amazon s3 to store our images/files. First, you need to sign up for Amazon.

You should follow this link to signup.  After successfully signing you can create your bucket. You can see the below image for better understanding.

create bucket account on amazon s3 cloud storage
create bucket account on amazon s3 cloud storage

Now You need to create a bucket policy, so you need to go to this link. And the page looks like this.

You can see the page looks like this.

You have created a bucket policy, Then copy-paste into a bucket policy. You can see the below image.

amazon s3 bucket policy

Now you will go here to get our Access Key Id and Secret Access Key.

Step 2 – Create PHP App

Visit your server directory; if you use xampp; So visit xampp/htdocs directory. And create a new directory which name file-upload-app.

Step 3 – Install AWS S3 PHP SDK

Execute the following command on the terminal to install aws s3 PHP SDK:

composer require aws/aws-sdk-php

Step 4 – Create File Upload Form

Create file/image upload HTML form; so visit your app root directory and create index.php file and add the following code into it:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>PHP File Upload Example - Tutsmake.com</title>
</head>
<body>
	<form action="upload-to-s3.php" method="post" enctype="multipart/form-data">
	    <h2>PHP Upload File</h2>
	    <label for="file_name">Filename:</label>
	    <input type="file" name="anyfile" id="anyfile">
	    <input type="submit" name="submit" value="Upload">
	    <p><strong>Note:</strong> Only .jpg, .jpeg, .gif, .png formats allowed to a max size of 5 MB.</p>
	</form>
</body>
</html>

Step 5 – Create upload-to-s3.php file

Create one file name upload-to-s3.php file and add the below code into your upload-to-s3.php .php file. The following PHP code uploads the files from the webserver with validation:

<?php

require 'vendor/autoload.php';
  
use Aws\S3\S3Client;

// Instantiate an Amazon S3 client.
$s3Client = new S3Client([
    'version' => 'latest',
    'region'  => 'YOUR_AWS_REGION',
    'credentials' => [
        'key'    => 'ACCESS_KEY_ID',
        'secret' => 'SECRET_ACCESS_KEY'
    ]
]);

// Check if the form was submitted
if($_SERVER["REQUEST_METHOD"] == "POST"){
    // Check if file was uploaded without errors
    if(isset($_FILES["anyfile"]) && $_FILES["anyfile"]["error"] == 0){
        $allowed = array("jpg" => "image/jpg", "jpeg" => "image/jpeg", "gif" => "image/gif", "png" => "image/png");
        $filename = $_FILES["anyfile"]["name"];
        $filetype = $_FILES["anyfile"]["type"];
        $filesize = $_FILES["anyfile"]["size"];
    
        // Validate file extension
        $ext = pathinfo($filename, PATHINFO_EXTENSION);
        if(!array_key_exists($ext, $allowed)) die("Error: Please select a valid file format.");
    
        // Validate file size - 10MB maximum
        $maxsize = 10 * 1024 * 1024;
        if($filesize > $maxsize) die("Error: File size is larger than the allowed limit.");
          
    
        // Validate type of the file
        if(in_array($filetype, $allowed)){
            // Check whether file exists before uploading it
            if(file_exists("upload/" . $filename)){
                echo $filename . " is already exists.";
            } else{
                if(move_uploaded_file($_FILES["anyfile"]["tmp_name"], "upload/" . $filename)){

                    $bucket = 'YOUR_BUCKET_NAME';
                    $file_Path = __DIR__ . '/upload/'. $filename;
                    $key = basename($file_Path);
                    
                    try {
                        $result = $s3Client->putObject([
                            'Bucket' => $bucket,
                            'Key'    => $key,
                            'Body'   => fopen($file_Path, 'r'),
                            'ACL'    => 'public-read', // make file 'public'
                        ]);
                        echo "Image uploaded successfully. Image path is: ". $result->get('ObjectURL');
                    } catch (Aws\S3\Exception\S3Exception $e) {
                        echo "There was an error uploading the file.\n";
                        echo $e->getMessage();
                    }
                    echo "Your file was uploaded successfully.";
                }else{

                   echo "File is not uploaded";
                }
                
            } 
        } else{
            echo "Error: There was a problem uploading your file. Please try again."; 
        }
    } else{
        echo "Error: " . $_FILES["anyfile"]["error"];
    }
}
?>

Note that:- Please add key, secret and bucket name in the above given code as shown below:

// Instantiate an Amazon S3 client.
$s3Client = new S3Client([
    'version' => 'latest',
    'region'  => 'YOUR_AWS_REGION',
    'credentials' => [
        'key'    => 'ACCESS_KEY_ID',
        'secret' => 'SECRET_ACCESS_KEY'
    ]
]);
  
  
$bucket = 'YOUR_BUCKET_NAME';

Conclusion

PHP upload file to amazon aws s3 bucket; Through this tutorial, you have learned how to upload file aws s3 bucket in PHP using aws-s3 PHP SDK.

Recommended PHP Tutorials

AuthorAdmin

My name is Devendra Dode. I am a full-stack developer, entrepreneur, and owner of Tutsmake.com. I like writing tutorials and tips that can help other developers. I share tutorials of PHP, Python, Javascript, JQuery, Laravel, Livewire, Codeigniter, Node JS, Express JS, Vue JS, Angular JS, React Js, MySQL, MongoDB, REST APIs, Windows, Xampp, Linux, Ubuntu, Amazon AWS, Composer, SEO, WordPress, SSL and Bootstrap from a starting stage. As well as demo example.

Leave a Reply

Your email address will not be published. Required fields are marked *