PHP Upload File to AWS S3 Bucket

PHP upload file to aws s3; Through this tutorial, i am going to show you how to upload or store image file into amazon aws s3 bucket using PHP.

An Amazon S3 bucket is a public cloud storage resource available in Amazon Web Services’ (AWS) Simple Storage Service (S3), an object storage offering. Amazon S3 buckets, which are similar to file folders, store objects, which consist of data and its descriptive metadata.

File Upload To AWS S3 Bucket in PHP

  • Step 1 – Start Apache Web Server
  • Step 2 – Create PHP Project
  • Step 3 – Install AWS S3 PHP SDK
  • Step 4 – Create AWS S3 Bucket Account
  • Step 5 – Create Image File Upload Html Form
  • Step 6 – Create upload-to-aws-s3.php file
  • Step 7 – Test This PHP App

Step 1 – Start Apache Web Server

Now, you need to start your apache web server. And as well as start Apache and mysql web server. You can see in the image below how to start apache and mysql server:

start xampp apache mysql server
start xampp apache mysql server

Step 2 – Create PHP Project

In step 2, navigate to your xampp/htdocs/ directory. And inside xampp/htdocs/ directory, create one folder. And you can name this folder anything.

Here, I will “demo” the name of this folder. Then open this folder in any text editor (i will use sublime text editor).

Step 3 – Install AWS S3 PHP SDK

In step 3, Open your terminal and execute the following command on it to install aws s3 php sdk:

composer require aws/aws-sdk-php

Step 4 – Create AWS S3 Bucket Account

In step 4, create amazon aws s3 bucket account; so follow the following steps and create aws s3 bucket account:

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 5 – Create Image File Upload Html Form

In step 5, create a php file that named index.php. Which is used to display image file upload form, So add the following code into it:

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <title>PHP File Upload to AWS S3 Bucket - Laratutorials.com</title>
</head>
<body>
	<form action="upload-to-aws-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 6 – Create upload-to-aws-s3.php file

In step 6, create one file that named upload-to-aws-s3.php .php file. This php file code will insert/store image file data into amazon aws s3 bucket.

So, add the below code into your upload-to-aws-s3.php file:

<?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:- add the aws key, secret and bucket name in the above code.

Step 7 – TestThis PHP App

Finally, you need to open your browser and type http://localhost/demo/ this run project on local machine.

Conclusion

PHP upload file to aws s3; Through this tutorial, You have learned how to upload or store image file into amazon aws s3 bucket using PHP.

Recommended PHP Tutorials

Be First to Comment

Leave a Reply

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