Home > Mobile >  PHP connect to aws. Connection refused
PHP connect to aws. Connection refused

Time:02-04

I can't connect to AWS S3 using the official PHP SDK from Amazon. This code

<?php
....

$s3Client = new S3Client([
    'version' => 'latest',
    'region' => 'us-east-1',
    'credentials' => [
        'key' => 'key',
        'secret' => 'secret',
    ],
]);

// Use the S3 client to perform actions, such as listing buckets
$result = $s3Client->listBuckets();
foreach ($result['Buckets'] as $bucket) echo $bucket['Name'] . "\n";

I get this error.

PHP Fatal error:  Uncaught exception 'Aws\S3\Exception\S3Exception' with message 'Error executing "ListBuckets" on "https://s3.amazonaws.com/"; AWS HTTP error: Connection refused for URI https://s3.amazonaws.com/'

GuzzleHttp\Exception\ConnectException: Connection refused for URI https://s3.amazonaws.com/ in C:\Users\bgaliev\PhpstormProjects\Cash2u.MigrationUtil\vendor\guzzlehttp\guzzle\src\Handler\StreamHandler.php:328
Stack trace:

I tried to do same thing using C#, that worked without any errors. Here is the basic sample code on C#

using Amazon;
using Amazon.Runtime;
using Amazon.S3;
using Amazon.S3.Model;

var amazonS3Client = new AmazonS3Client(
    new BasicAWSCredentials("key", "secret"),
    new AmazonS3Config
    {
        RegionEndpoint = RegionEndpoint.USEast1
    }
);


var listBuckets = await amazonS3Client.ListBucketsAsync(new ListBucketsRequest());

foreach (var listBucketsBucket in listBuckets.Buckets)
{
    Console.WriteLine(listBucketsBucket.BucketName);
}

CodePudding user response:

In my experience you need to declare an object of AWS Credentials class first

So for your case, please change to something like:

<?php
....

$credentials = new Aws\Credentials\Credentials('key', 'secret');

$s3Client = new Aws\S3\S3Client([
    'version'     => 'latest',
    'region'      => 'us-east-1',
    'credentials' => $credentials
]);

CodePudding user response:

Refer to the PHP S3 example in AWS Github that specifies how to use the S3Client to perform this use case.

Notice the mention about creds in this doc topic:

https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials.html

require 'vendor/autoload.php';

use Aws\S3\S3Client;  
use Aws\Exception\AwsException;
// snippet-end:[s3.php.list_buckets.import]


/**
 * List your Amazon S3 buckets.
 *
 * This code expects that you have AWS credentials set up per:
 * https://docs.aws.amazon.com/sdk-for-php/v3/developer-guide/guide_credentials.html
 */

//Create a S3Client 
// snippet-start:[s3.php.list_buckets.main]
$s3Client = new S3Client([
    'profile' => 'default',
    'region' => 'us-west-2',
    'version' => '2006-03-01'
]);

//Listing all S3 Bucket
$buckets = $s3Client->listBuckets();
foreach ($buckets['Buckets'] as $bucket) {
    echo $bucket['Name'] . "\n";
}
  • Related