无法使用aws-php-sdk连接到AWS s3。非法请求

时间:2017-04-27 09:36:20

标签: php amazon-web-services amazon-s3 aws-sdk

我的错误讯息:

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

我的代码:

<?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'];

无法弄清楚为什么我无法通过。我的电话中有正确的参数。我的代码主要是从他们的aws-sdk-php示例页面复制而来。所以它不应该是那里的错。

我正在使用aws cli并在~/.aws/下设置了upp我的配置和凭据文件

修改

搞定了!这是我现在的代码:

<?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";
}

1 个答案:

答案 0 :(得分:0)

试试这个,肯定会有效,代码中的问题是你没有提供factory功能的凭据。

<?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'];