AWS PHP SDK - S3 failing silently - php

So I have a block of code to upload an image to an S3 Bucket. It's fairly boilerplate. Works perfectly running from localhost.
I push it to my Ubuntu EC2 server, and the code fails. No error, no exceptions, Debug => true outputs nothing.. Trying to var_dump the $s3Client variable reports nothing.
E_ALL Error reporting is on
PHP 8.1.4
Nginx 1.21.6
Compatability-test.php passes successfully - all required modules enabled.
Code:
<?php
require 'S3/aws-autoloader.php';
use Aws\S3\S3Client;
use Aws\S3\Exception\S3Exception;
$bucket = 'XXXXX';
try {
//Create a S3Client
$s3Client = new S3Client([
'profile' => 'default',
'region' => 'us-east-1',
'version' => '2006-03-01',
'signature' => 'v4',
'debug' => true,
'credentials' => [
'key' => XXXXX,
'secret' => XXXXX,
]
]);
$result = $s3Client->putObject([
'Bucket' => $bucket,
'Key' => $fileName,
'SourceFile' => $filePath,
'ACL' => 'public-read'
]);
echo json_encode(array('success' => true, 'imageUrl' => $result->get('ObjectURL')));
} catch (S3Exception $exception) {
echo $exception->getMessage() . "\n";
}
Has anyone else experienced this 'quiet failure' with the AWS PHP-SDK S3?

I solved this, after 3 days. There were several problems, which I managed to solve and inspect by running the code from the PHP CLI.
First things to note:
Credentials must be stored in the /var/www/.aws/credentials file. This is where the S3Client class will look for your S3 credentials. Passing them into the S3 class instantiation does not appear to work.
Running from the CLI, indicated that I was missing the PHP module mbstring. I don't know why Amazon's compatibility-test.php file does not flag this module as missing. Go figure.
Why the script failed silently, I really don't know. Maybe some error suppression somewhere in the S3Client class. I highly recommend running from the PHP-CLI to diagnose any errors with the PHP AWS S3 SDK.

I realize this is a bit late, but I experienced a similar issue recently where specifically I did not want to use the credentials file, whereas your answer notes that the credentials must be stored in the credentials file.
In my experience, what wound up working for me was removing the 'profile' => 'default', in the s3Client creation. So like this ...
//Create a S3Client
$s3Client = new S3Client([
'region' => 'us-east-1',
'version' => '2006-03-01',
'signature' => 'v4',
'debug' => true,
'credentials' => [
'key' => XXXXX,
'secret' => XXXXX,
]
]);
So if you minimally want to use the inline credentials instead of the credentials file, this may help you out a bit.

Related

AWS S3Client PHP suddenly doesn't work anymore

today my web site which usually auto logs to aws s3 by php, can't connect anymore; the code hasn't changed at all.
$s3Client = new S3Client([
'region' => 'eu-west-1',
'version' => 'latest',
'credentials' => [
'key' => $key,
'secret' => $secret,
],
'http' => [
'verify' => '../ssl_crt/cacert.pem'
]
]);
//echo var_dump($s3Client);
//Listing all S3 Bucket
$result = $s3Client->listBuckets();
the code above which has worked fine till yesterday now gets tomeout connection and therefore fails listing buckets.
I have read amazon has changed something in the permissions/policy, but I can't find how this can be related to PHP s3Client... maybe I could just change some setting in AWS S3 control panel, but I can't figure out what...Has anyone experienced the same issue

Laravel Storage Filesystem and Amazon S3 gives CredentialsException

I'm trying to use Filesystem, the implementation of league/flysystem-aws-s3-v3 with Laravel 5.1. but I can get the files from S3.
So, I coded this:
$s3 = Storage::disk('s3');
$imageName = Employee::filePath() . $employee->id . '.pdf';
if (Storage::disk('s3')->exists($imageName)) {
return response()->download(Storage::disk('s3')->get($imageName));
}
Then I get the follow error:
CredentialsException in InstanceProfileProvider.php line 79:
Error retrieving credentials from the instance profile metadata server. (cURL error 28: Connection timed out after 1001 milliseconds (see http://curl.haxx.se/libcurl/c/libcurl-errors.html))
The credential are set on config/filesystems.php, I know are good because I can put files there.
Do you have any idea?
Thanks in advance.
The problem was with my configuration, I was trying to setup with env, however for some reason doesn't load at moment of configuration, so I decide put directly on the configuration file filesystems.php
's3' => [
'driver' => 's3',
'key' => 'XXXXXXXXXX',
'secret' => 'XXXXXXXXXX',
'region' => env('S3_REGION'),
'bucket' => env('S3_BUCKET'),
],

Missing required client configuration options: region

I am trying to check bucket existence on Amazon S3 using below code:
$credentials = new Aws\Common\Credentials\Credentials($creds['access_key_id'], $creds['secret_access_key']);
$client = Aws\S3\S3Client::factory(array( 'credentials' => $credentials ) );
if( ! $client->doesBucketExist($creds['bucket']) ) {
throw new Exception("Bucket (" . $creds['bucket'] . ") does not exist.");
}
It is working on localhost (wamp) but when I tried this on server it is not working. I am getting following error:
Missing required client configuration options: region: (string) A "region" configuration value is required for the "s3" service (e.g., "us-west-2"). A list of available public regions and endpoints can be found at http://docs.aws.amazon.com/general/latest/gr/rande.html. version: (string) A "version" configuration value is required. Specifying a version constraint ensures that your code will not be affected by a breaking change made to the service. For example, when using Amazon S3, you can lock your API version to "2006-03-01". Your build of the SDK has the following version(s) of "s3": * "2006-03-01" You may provide "latest" to the "version" configuration value to utilize the most recent available API version that your client's API provider can find. Note: Using 'latest' in a production application is not recommended. A list of available API versions can be found on each client's API documentation page: http://docs.aws.amazon.com/aws-sdk-php/v3/api/index.html. If you are unable to load a specific API version, then you may need to update your copy of the SDK.
I don't know why it is not working on server but same code is working on localhost.
I had the same problem and I needed to clear my config cache to fix it.
$ artisan config:clear
Set region explicitly when creating s3 client instead of relying on defaults.
use Aws\Credentials\Credentials;
use Aws\S3\S3Client;
$result = $stsClient->getSessionToken();
$credentials = new Credentials(
$result['Credentials']['AccessKeyId'],
$result['Credentials']['SecretAccessKey'],
$result['Credentials']['SessionToken']
);
$s3Client = new S3Client([
'version' => '2006-03-01',
'region' => 'us-west-2',
'credentials' => $credentials
]);
Check .env file variables are matching with filesystems.php
's3' => [
'driver' => 's3',
'key' => env('S3_KEY'),
'secret' => env('S3_SECRET'),
'region' => env('S3_REGION'),
'bucket' => env('S3_BUCKET'),
],
1) Ensure you have S3_KEY, S3_SECRET, S3_REGION, S3_BUCKET etc configured in your .env file
2) Your environment file might have changed after the autoload/caches were generated. Run:
php artisan config:cache

Client credentials not retrived when attempting to use aws php sdk

I am attempting to connect to a DynamoDB hosted on aws using php.
I am currently getting the following error:
Fatal error: Uncaught exception 'Aws\Exception\CredentialsException'
with message 'Error retrieving credentials from the instance profile
metadata server. (cURL error 28: Connection timed out after 1000
milliseconds (see
http://curl.haxx.se/libcurl/c/libcurl-errors.html))' in
C:\wamp\www\Aws\Credentials\InstanceProfileProvider.php on line 79
I've taken this to mean there are issues with my client credentials which I need to use the sdk. My credentials are coded as follows:
$client = new DynamoDbClient([
'profile' => 'my profile',
'region' => 'us-west-2',
'version' => 'latest',
'credentials' => [
'key' => 'my key',
'secret' => 'my secret key',
]
]);
From what I've seen this error usually means there is a problem with the way the credentials are formatted, but as far as I can tell I don't have that issue. I'm currently trying to run this program locally using wamp. I'm not sure what the problem is.
Please try below steps and check if it work correctly :
1) Download aws php sdk here.
2) Unzip and require autoloader.php and use dynamodb client.
require_once 'PATH/TO/aws-autoloader.php';
use Aws\DynamoDb\DynamoDbClient;
3) initiate dynamo db client
try
{
$aws = DynamoDbClient::factory(array(
'key' => $aws_key,
'secret' => $aws_access_key,
'region' => $aws_region
));
echo "Client initiated";
}
catch(Exception $e)
{
echo "Db Client initiation failed ".$e->getMessage();
}
4) Check this for api's

setting up cloudfront with php sdk

I am trying to configure the the amazon cloud front, I have successfully created clouldflayer url and access private s3 bucket from it via console. Now I am trying to do it by php-sdk for that I have tried following code
use Aws\CloudFront\CloudFrontClient;
$cle = new CloudFrontClient([
'version' => 'latest',
'region' => 'us-west-2',
'credentials.ini' => [
'key' => 'credentials\pk-myKey.pem',
'secret' => 'secret',
],
]);
$result = $cle->getCloudFrontOriginAccessIdentity([
'Id' => '****', // REQUIRED
]);
print_r($result);
but I am getting error
Fatal error: Uncaught exception 'Aws\CloudFront\Exception\CloudFrontException' with message 'Error executing "GetCloudFrontOriginAccessIdentity" on "https://cloudfront.amazonaws.com/2015-04-17/origin-access-identity/cloudfront/SDF345G";
AWS HTTP error: Client error: 403 SignatureDoesNotMatch (client): Credential should be scoped to a valid region, not 'us-west-2'. -
and I have tried all reason one by one but its not working
Credential should be scoped to a valid region, not 'us-west-2'.
Unlike most of AWS, CloudFront is not a regional service, it's a global one, configured and managed through us-east-1, regardless of the region where any of the related services (S3, EC2, etc.) are deployed.
'region' => 'us-east-1',

Categories