Skip to content

Instantly share code, notes, and snippets.

@keithweaver
Created July 18, 2017 11:33
Show Gist options
  • Star 25 You must be signed in to star a gist
  • Fork 20 You must be signed in to fork a gist
  • Save keithweaver/70eb06d98b008113ce97f6148fbea83d to your computer and use it in GitHub Desktop.
Save keithweaver/70eb06d98b008113ce97f6148fbea83d to your computer and use it in GitHub Desktop.
Upload image using form submission to AWS S3 with PHP
<?php
// This file demonstrates file upload to an S3 bucket. This is for using file upload via a
// file compared to just having the link. If you are doing it via link, refer to this:
// https://gist.github.com/keithweaver/08c1ab13b0cc47d0b8528f4bc318b49a
//
// You must setup your bucket to have the proper permissions. To learn how to do this
// refer to:
// https://github.com/keithweaver/python-aws-s3
// https://www.youtube.com/watch?v=v33Kl-Kx30o
// I will be using composer to install the needed AWS packages.
// The PHP SDK:
// https://github.com/aws/aws-sdk-php
// https://packagist.org/packages/aws/aws-sdk-php
//
// Run:$ composer require aws/aws-sdk-php
require 'vendor/autoload.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
// AWS Info
$bucketName = 'SUB_YOUR_BUCKET_NAME_IN';
$IAM_KEY = 'SUB_YOUR_IAM_KEY_IN';
$IAM_SECRET = 'SUB_YOUR_IAM_SECRET_IN';
// Connect to AWS
try {
// You may need to change the region. It will say in the URL when the bucket is open
// and on creation.
$s3 = S3Client::factory(
array(
'credentials' => array(
'key' => $IAM_KEY,
'secret' => $IAM_SECRET
),
'version' => 'latest',
'region' => 'us-east-2'
)
);
} catch (Exception $e) {
// We use a die, so if this fails. It stops here. Typically this is a REST call so this would
// return a json object.
die("Error: " . $e->getMessage());
}
// For this, I would generate a unqiue random string for the key name. But you can do whatever.
$keyName = 'test_example/' . basename($_FILES["fileToUpload"]['tmp_name']);
$pathInS3 = 'https://s3.us-east-2.amazonaws.com/' . $bucketName . '/' . $keyName;
// Add it to S3
try {
// Uploaded:
$file = $_FILES["fileToUpload"]['tmp_name'];
$s3->putObject(
array(
'Bucket'=>$bucketName,
'Key' => $keyName,
'SourceFile' => $file,
'StorageClass' => 'REDUCED_REDUNDANCY'
)
);
} catch (S3Exception $e) {
die('Error:' . $e->getMessage());
} catch (Exception $e) {
die('Error:' . $e->getMessage());
}
echo 'Done';
// Now that you have it working, I recommend adding some checks on the files.
// Example: Max size, allowed file types, etc.
?>
@Braiderp
Copy link

Can you please explain to me why you have 2 tries and 3 catches? Also why do you use S3Exception sometimes and just Exception other times?

@krishnkant1996
Copy link

I'm facing a problem
Error:Unable to open b3.png using mode r: fopen(b3.png): failed to open stream: No such file or directory

@nilchen
Copy link

nilchen commented Feb 11, 2019

goog job!
working!
if you want to upload origin file name...
Using
$keyName = 'test_demo/' . basename($_FILES["file"]['name']); # tmp_name

@nilchen
Copy link

nilchen commented Feb 11, 2019

I'm facing a problem
Error:Unable to open b3.png using mode r: fopen(b3.png): failed to open stream: No such file or directory
check $_FILES["fileToUpload"]
//--

$keyName = 'test_example/' . basename($_FILES["fileToUpload"]['tmp_name']);
2.
// Uploaded:
$_FILES["fileToUpload"]['tmp_name'];
//--
and echo it
$keyName = 'test_demo/' . basename($_FILES["file"]['name']);
echo $keyName;

@mayurdonga13
Copy link

i have fetched below error on aws/aws-sdk-php
Parse error: syntax error, unexpected ':', expecting '{' in /home/galaxlmm/public_html/artsoftdata.com/amazons3/vendor/guzzlehttp/guzzle/src/functions.php on line 14

@renansa27
Copy link

Can you please explain to me why you have 2 tries and 3 catches? Also why do you use S3Exception sometimes and just Exception other times?

I believe that the first catch is to exceptions unique to AWS, the second is PHP exceptions

@gtvet
Copy link

gtvet commented Feb 26, 2021

You r rocking man. I was facing an issue of inode count in my existing hostgator account. Now I have swichted to AWS S3 and uploaded photos using api with your tutorials

@cosoriond
Copy link

Hil! could yo help me with this error:

SignatureDoesNotMatchThe request signature we calcul (truncated...) SignatureDoesNotMatch (client): The request signature we calculated does not match the signature you provided. Check your key and signing method. - SignatureDoesNotMatchThe request signature we calculated does not match the signature you provided. Check your key and signing method.

@gwatai
Copy link

gwatai commented Jul 2, 2022

I'm facing a problem Error:Unable to open b3.png using mode r: fopen(b3.png): failed to open stream: No such file

i ma still facing this error kindly help

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment