0

I want to upload image files directly to S3 without storing them on my server (for security). How can I do that with the PHP SDK from AWS S3? here is an example code:

<?php
require_once '/var/www/site/vendor/autoload.php';

use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;

$bucket = '<your bucket name>';
$keyname = 'sample';
$filepath = '/path/to/image.jpg';

// Instantiate the client.
$s3 = S3Client::factory(array(
    'key'    => 'your AWS access key',
    'secret' => 'your AWS secret access key'
));

try {
    $result = $s3->putObject(array(
        'Bucket' => $bucket,
        'Key'    => $keyname,
        'SourceFile'   => $filepath,
        'ACL'    => 'public-read'
    ));

    echo 'Success';
} catch (S3Exception $e) {
    echo $e->getMessage() . "\n";
}

Here is the upload form:

<form action="upload.php" method="post" enctype="multipart/form-data">
    <input type="file" name="image" id="image">
    <input type="submit" value="Upload Image" name="submit">
</form>

What would I put for $filepath in the PHP code since I don't want to store it on my server for security reason (I don't want it to execute malicious code and stuff like that)? Any help would be appreciated thanks!

2
  • Can you post the form/html where the image comes from? Commented Jul 28, 2019 at 21:15
  • @atymic yes I added that in Commented Jul 28, 2019 at 21:19

1 Answer 1

2

PHP's built in file upload handling will make this very easy. When a request is received with a file, PHP automatically moves it to temporary location & makes it's metadata accessible using $_FILES.

You can then do something like below to upload the file to s3:

<?php
if(empty($_FILES['image'])){
    die('Image missing');
}

$fileName = $_FILES['image']['name'];
$tempFilePath = $_FILES['image']['tmp_name'];

require 'vendor/autoload.php';

$s3 = S3Client::factory(array(
    'key'    => 'your AWS access key',
    'secret' => 'your AWS secret access key'
));

try {
    $result = $s3->putObject(array(
        'Bucket' => '<your bucket>',
        'Key'    => $fileName,
        'SourceFile'   => $tempFilePath,
        'ACL'    => 'public-read'
    ));

    echo 'Success';
} catch (S3Exception $e) {
    echo $e->getMessage() . "\n";
}
Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.