Upload file to S3 Bucket with AWS SDK NoSuchBucket error - php

Tried to upload file to S3 Bucket, i set up the SDK using the following code:
<?php
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
try {
require 'vendor/autoload.php';
$s3 = new Aws\S3\S3Client([
'region' => 'us-east-1',
'version' => 'latest',
'credentials' => [
'key' => "KEY",
'secret' => "SECRET",
]
]);
$result = $s3->putObject([
'Bucket' => 'bucketname',
'Key' => 'test.txt',
'SourceFile' => 'test.txt'
]);
var_dump($result);
} catch (\Throwable $th) {
echo $th;
}
Error log
AWS HTTP error: Client error: `PUT https://bucketname.s3.amazonaws.com/test.txt` resulted in a `404 Not Found` response: NoSuchBucketThe specified bucket does not exist
Possible errors:
The URL should be this form based on:
Documentation
https://s3.Region.amazonaws.com/bucket-name/key name

I think the trouble is with the S3 Client itself. Below is the example from the documentation PutObject.php
use Aws\S3\S3Client;
use Aws\Exception\AwsException;
....
try {
//Create a S3Client
$s3Client = new S3Client([
'profile' => 'default',
'region' => 'us-west-2',
'version' => '2006-03-01'
]);
$result = $s3Client->putObject([
'Bucket' => $bucket,
'Key' => $key,
'SourceFile' => $file_Path,
]);
} catch (S3Exception $e) {
echo $e->getMessage() . "\n";
}

Related

Upload URL image to s3

I'm trying to upload an image from an external url (another website) to my s3. this is what I've done so far.
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
// AWS Info
$bucketName = 'my-bucket';
$IAM_KEY = 'XXXXXXXXXXXX';
$IAM_SECRET = 'XXXXXXXXXXXX';
// Connect to AWS
try {
$s3 = new S3Client(
[
'credentials' => [
'key' => $IAM_KEY,
'secret' => $IAM_SECRET
],
'version' => 'latest',
'region' => 'ap-southeast-1'
]
);
} catch (Exception $e) {
die("Error: " . $e->getMessage());
}
$binary = file_get_contents('https://blabla.com/imgs.jpg');
$filename = '/storage/test.jpg';
$response = $s3->putObject(
[
'Bucket' => $bucketName,
'Key' => 'obj-'.ceil(rand(1,100000)),
'SourceFile' => $filename,
'Body' => $binary,
'ContentType' => 'image/jpg',
'StorageClass' => 'REDUCED_REDUNDANCY'
]
);
dd($response);
when i run the code, i get this error
Unable to open "test.jpg" using mode "r": fopen(test.jpg): Failed to open stream: No such file or directory
how do i upload to s3? Thank you.

Can't Upload File to Amazon S3

I have a problem when I trying uploading objects to my amazon s3 bucket. It always shows error and it has s3 on the url.
"Error executing "PutObject" on
"https://bucketname.s3.s3-ap-southeast-1.amazonaws.com/WIN_20171117_16_45_59_Pro.jpg";
AWS HTTP error: cURL error 51: SSL: no alternative certificate subject
name matches target host name
'bucketname.s3.s3-ap-southeast-1.amazonaws.com' (see
http://curl.haxx.se/libcurl/c/libcurl-errors.html)"
Here's my code for uploading images to the amazon s3
require "aws/aws-autoloader.php";
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
$client = S3Client::factory(
array(
'credentials' => array(
'key' => $key,
'secret' => $secret
),
'version' => 'latest',
'region' => 's3-ap-southeast-1'
)
);
try {
$client->putObject(array(
'Bucket'=>$bucket,
'Key' => $keyname,
'SourceFile' => $sourcefile,
'StorageClass' => 'REDUCED_REDUNDANCY',
'ContentType' => 'image',
'ACL' => 'public-read'
));
} catch (S3Exception $e) {
// Catch an S3 specific exception.
echo $e->getMessage();
}
Try using ap-southeast-1 as the region instead of s3-ap-southest-1.

Delete a file from s3 bucket

I've created an upload and download service in php-symfony2. This is working fine. Now I want to delete the uploaded file. Any Example?
Note: No data storing to database tables.
Deleting One Object (Non-Versioned Bucket)
Create instance of S3 client using Aws\S3\S3Client class factory().
$s3 = S3Client::factory();
Execute the Aws\S3\S3Client::deleteObject() method with bucket name and a key name.
$result = $s3->deleteObject(array(
'Bucket' => $bucket,
'Key' => $keyname
));
If versioning is enabled DELETE MARKER Will be added. (References)
EXAMPLE
<?php
require 'vendor/autoload.php';
use Aws\S3\S3Client;
$s3 = S3Client::factory();
$bucket = '*** Your Bucket Name ***';
$keyname = '*** Your Object Key ***';
$result = $s3->deleteObject(array(
'Bucket' => $bucket,
'Key' => $keyname
));
More References can be found here.
You can use deleteObject() method, refer the doc.
use Aws\S3\S3Client;
$s3 = S3Client::factory();
$bucket = '*** Your Bucket Name ***';
$keyname = '*** Your Object Key ***';
$result = $s3->deleteObject(array(
'Bucket' => $bucket,
'Key' => $keyname
));
After lot of solution i tried i found the solution that works for me perfectly.
$s3 = Storage::disk('s3');
$s3->delete('filename');
You can use the aws s3 delete API method which delete the uploaded file. you can achieve it like below.
use Aws\S3\S3Client;
$s3 = new S3(awsAccessKey, awsSecretKey);
$s3->deleteObject("bucketname", filename);
This Code Worked For me.
$s3Client = new S3Client([
'version' => 'latest',
'region' => 'your region',
'credentials' => [
'key' => '**AWS ACCESS KEY**',
'secret' => '**AWS SECRET ACCESS KEY**',
],
]);
try {
$result = $s3Client->deleteObject(array(
'Bucket' => '**YOUR BUCKET**',
'Key' => "videos/file.mp4"
));
return 1;
} catch (S3Exception $e) {
return $e->getMessage() . PHP_EOL;
}
Unfortunately, Arsalan's answer doesn't appear to work anymore. What worked for me, using access and secret keys was:
$this->s3 = new S3Client([
'driver' => 's3',
'version' => 'latest',
'region' => env('AWS_DEFAULT_REGION'),
'credentials' => [
'key' => env('AWS_ACCESS_KEY_ID'),
'secret' => env('AWS_SECRET_ACCESS_KEY')
]
]);
$this->s3->putObject([
'Bucket' => env('AWS_BUCKET'),
'Key' => env('AWS_SECRET_ACCESS_KEY'),
'Body' => $body,
'Key' => $key
]);

Cant connect to AWS s3, using aws-php-sdk. Invalid Request

My error message:
Uncaught Aws\S3\Exception\InvalidRequestException:
AWS Error Code: InvalidRequest,
Status Code: 400, AWS Request ID: xxx,
AWS Error Type: client,
AWS Error Message: The authorization mechanism you have provided is not supported.
Please use AWS4-HMAC-SHA256., User-Agent: aws-sdk-php2/2.7.27 Guzzle/3.9.3 curl/7.47.0 PHP/7.0.15-0ubuntu0.16.04.4
My Code:
<?php
use Aws\S3\S3Client;
require 'vendor/autoload.php';
$config = array(
'key' => 'xxx',
'secret' => 'xxx',
'bucket' => 'myBucket'
);
$filepath = '/var/www/html/aws3/test.txt';
//s3
// Instantiate the client.
$s3 = S3Client::factory();
// Upload a file.
$result = $s3->putObject(array(
'Bucket' => $config['bucket'],
'Key' => $config['key'],
'SourceFile' => $filepath,
'Endpoint' => 's3-eu-central-1.amazonaws.com',
'Signature'=> 'v4',
'Region' => 'eu-central-1',
//'ContentType' => 'text/plain',
//'ACL' => 'public-read',
//'StorageClass' => 'REDUCED_REDUNDANCY',
//'Metadata' => array(
// 'param1' => 'value 1',
// 'param2' => 'value 2'
)
);
echo $result['ObjectURL'];
Cant figure out why I cant get through. I have the right parameters in my call. My code is mostly copied from their aws-sdk-php example page. So it shouldnt be to much fault there.
I am using aws cli and have set upp my configure and credentials file under ~/.aws/
EDIT:
Got it to work! This is my code now:
<?php
// Get dependencies
use Aws\S3\S3Client;
require 'vendor/autoload.php';
// File to upload
$filepath = '/var/www/html/aws3/test.txt';
// instantiate the Client
$s3Client = S3Client::factory(array(
'credentials' => array(
'key' => 'AKIAJVKBYTTADILGRTVQ',
'secret' => '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'
),
'region' => 'eu-central-1',
'version' => 'latest',
'signature_version' => 'v4'
));
// Upload a file.
$result = $s3Client->putObject(array(
'Bucket' => "myBucket",//some filebucket name
'Key' => "some_file_name.txt",//name of the object with which it is created on s3
'SourceFile' => $filepath,
)
);
// Echo results
if ($result){
echo $result['ObjectURL'];
} else{
echo "fail";
}
Try this, it will surely work, the problem in your code is you haven't supplied credentials to factory function.
<?php
ini_set('display_errors', 1);
use Aws\S3\S3Client;
require 'vendor/autoload.php';
//here we are creating client object
$s3Client = S3Client::factory(array(
'credentials' => array(
'key' => 'YOUR_AWS_ACCESS_KEY_ID',
'secret' => 'YOUR_AWS_SECRET_ACCESS_KEY',
)
));
// Upload a file.
$filepath = '/var/www/html/aws3/test.txt';
$result = $s3Client->putObject(array(
'Bucket' => "myBucket",//some filebucket name
'Key' => "some_file_name.txt",//name of the object with which it is created on s3
'SourceFile' => $filepath,
'Endpoint' => 's3-eu-central-1.amazonaws.com',
'Signature' => 'v4',
'Region' => 'eu-central-1',
)
);
echo $result['ObjectURL'];

Deleting a bucket on Amazon S3 AWS SDK for PHP - Version 3?

I see lots of tutorials even on Amazon to get this done. I follow it but for some reason it doesn't work.
I can do the other command below that works great, but deleting a bucket is not working, with no output for errors.
require 'vendor/autoload.php';
$key = 'file.txt'; // filename
$bucket = 'BUCKETNAME';
use Aws\S3\S3Client;
$client = S3Client::factory([
'version' => 'latest',
'region' => 'us-east-1',
'credentials' => [
'key' => 'KEY',
'secret' => 'SECRET'
]
]);
$result = $client->deleteObject(array(
'Bucket' => $bucket,
'Key' => $key
));
This works, but it isn't a delete command (GetObject) :
$cmd = $client->getCommand('GetObject', [
'Bucket' => $bucket,
'Key' => 'file.txt'
]);
$request = $client->createPresignedRequest($cmd, '+20 minutes');
echo $presignedUrl = (string) $request->getUri();
To delete a bucket:
// Delete the bucket
$client->deleteBucket(array('Bucket' => $bucket));
You are missing the array.
Here:
http://docs.aws.amazon.com/aws-sdk-php/v2/guide/service-s3.html#cleaning-up

Categories