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.
Related
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";
}
I'm using amazon s3 as video storage for my website. I'm having problems for some videos. black screen or sound problems etc.
I want to convert the video to mp4 format after uploading the video to my server and then upload it to amazon. Is it possible with FFMPEG?
I'm using this code for uploading files now:
$file1 = $_FILES['file']['name'];
$videoFileType = strtolower(pathinfo($file1,PATHINFO_EXTENSION));
$file_name = sprintf('%s_%s', uniqid(),uniqid().".".$videoFileType);
$temp_file_location = $_FILES["file"]["tmp_name"];
require 'application/libraries/Amazon/aws-autoloader.php';
$s3 = new Aws\S3\S3Client([
'region' => $amazon_region,
'version' => 'latest',
'credentials' => [
'key' => $amazon_key,
'secret' => $amazon_secret,
]
]);
$result = $s3->putObject([
'Bucket' => $amazon_bucket,
'Key' => $file_name,
'SourceFile' => $temp_file_location,
'ACL' => 'public-read',
'CacheControl' => 'max-age=3153600',
]);
$filepath = $result['ObjectURL'] . PHP_EOL;
echo json_encode([
'status' => 'ok',
'path' => $filepath
]);
I am uploading files from php to aws s3. I have successfully uploaded the file.
The url it is returning is => https://BUCKETNAME.s3.ap-south-1.amazonaws.com/images1740/1550830121572.jpg
The actual url is => https://s3.ap-south-1.amazonaws.com/BUCKETNAME/images1740/1550830121572.jpg
(bucket name is coming in starting instead at the end of url)
Because of this it is giving me error while loading images => "Specified Key not found"
$source = $source;
$bucket = 'xxxxxxxxxxxxxxxxx';
$keyname = 'images'.$usr_id."/".$name;
// for push
$s3 = S3Client::factory(
array(
'credentials' => array(
'key' => "xxxxxxxxxxxxxx",
'secret' => "xxxxxxxxxxxxxxx"
),
'version' => 'latest',
'region' => 'ap-south-1'
)
);
try {
// Upload data.
$result = $s3->putObject(array(
'Bucket' => $bucket,
'Key' => $keyname,
'SourceFile' => $source,
'ServerSideEncryption' => 'AES256',
));
// Print the URL to the object.
print_r($result);
return $result['ObjectURL'] . PHP_EOL;
// print_r($result);
} catch (S3Exception $e) {
echo $e->getMessage() . PHP_EOL;
}
Set use_path_style_endpoint to true when initializing the S3 client to have it use the S3 path style endpoint by default when building the object URL. 1
Implementation details has the object URL to be in the path style if the bucket name makes a valid domain name otherwise it fallback to the S3 path style.
You want to keep the later behavior all the time.
$s3 = S3Client::factory(
array(
'credentials' => array(
'key' => "xxxxxxxxxxxxxx",
'secret' => "xxxxxxxxxxxxxxx"
),
'use_path_style_endpoint' => true,
'version' => 'latest',
'region' => 'ap-south-1'
)
);
You can also do as below if you wanted to disable it one-time for the PutObject operation.
$result = $s3->putObject(array(
'Bucket' => $bucket,
'Key' => $keyname,
'SourceFile' => $source,
'ServerSideEncryption' => 'AES256',
'#use_path_style_endpoint' => true
));
Here I have the code of connection
$s3 = S3Client::factory(array(
'key' => 'xxxxxxxxx',
'secret' => '0xxxxxxxxxx',
'version' => 'latest',
'region' => 'us-west-2',
))
Here the bucket name $bucket = 'ariana-ios-storages'; and here the name of file $p = parse_url($images->name) which is the
name of file in amazon to delete;
Here is the code to delete the file
$delete = $s3->deleteObject([
'Bucket' => $bucket,
'Key' => $p['path']
]);
var_dump($delete);
exit();
The file path is generated like this;
It is not deleting the single file from the bucket so can any one help what i am missing
public function actionDeleteImages($id)
{
$exportImage= \common\models\ExportImages::findOne($id);
$base_url='base url to bucket';
$s3 = S3Client::factory(array(
'key' => 'xxxxxxx',
'secret' => '0pdfOx21xxxxxxxxxx',
'version' => 'latest',
'region' => 'us-west-2',
));
$bucket = 'name of bucket';
$key=urldecode(explode($base_url,$exportImage->name)[1]);// $images->name is Path from Db, base url is path to s3 server
$delete = $s3->deleteObject([
'Bucket' => 'ariana-ios-storages',
'Key' => $key
]);
$object_exist = $s3->doesObjectExist($bucket,$key);
if(!$object_exist){
return "succesfully deleted";
}else{
return "there is some problem while procesing the deletion";
}
}
}
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'];