Featured image of post Example of Uploading Files to AWS S3 Storage using PHP

Example of Uploading Files to AWS S3 Storage using PHP

An example of PHP receiving HTML form uploads and storing them in AWS S3. Let's start with a simple HTML upload code...

Here’s an example of using PHP to receive file uploads from an HTML form and store them in AWS S3.

First, let’s create a simple HTML upload form that will allow PHP to handle the file upload. In the HTML page, we will create a basic form for selecting the file to upload.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
<!-- index -->
<!DOCTYPE html>
<html>
<head>
    <meta charset="UTF-8">
    <title>Upload File</title>
</head>
<body>
    <form action="upload.php" method="post" enctype="multipart/form-data">
        <input type="file" name="file">
        <button type="submit">Upload File</button>
    </form>
</body>
</html>

In the code above, we use the <form> tag to upload the file to the upload.php script, applying the enctype="multipart/form-data" attribute to specify the form data type as multipart/form-data, which supports file uploads.

Next, in PHP, we will utilize the AWS SDK for PHP library to upload the file to S3.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
<?php
// upload.php

require 'vendor/autoload.php'; // Include the AWS SDK for PHP library

use Aws\S3\S3Client;

if ($_SERVER['REQUEST_METHOD'] === 'POST') {
    if (isset($_FILES['file'])) {
        $bucketName = 'your-bucket-name'; // Replace with your S3 bucket name
        $s3Key = 'uploads/' . basename($_FILES['file']['name']);
        $file = $_FILES['file']['tmp_name'];

        $s3 = new S3Client([
            'version' => 'latest',
            'region' => 'your-region', // Replace with your S3 bucket region
            'credentials' => [
                'key' => 'your-access-key',
                'secret' => 'your-secret-key',
            ],
        ]);

        try {
            $s3->putObject([
                'Bucket' => $bucketName,
                'Key' => $s3Key,
                'Body' => fopen($file, 'r'),
                'ACL' => 'public-read', // Set to public-read
            ]);
            echo 'File upload successful';
        } catch (Exception $e) {
            echo 'File upload failed: ' . $e->getMessage();
        }
    } else {
        echo 'No file selected for upload';
    }
} else {
    echo 'Invalid request method';
}

In the PHP code above, we first include the AWS SDK for PHP library and create an S3 client object as needed. We then retrieve the uploaded file from the $_FILES global variable and use the S3 client object to upload the file to the specified bucket.

Please note that you need to create an S3 bucket in AWS first and set the appropriate access permissions. In this example, we have configured the uploaded file to be publicly readable.

Licensed under CC BY-NC-SA 4.0