简体   繁体   English

在 EC2 实例上使用 PHP 将文件上传到 s3 抛出凭据错误,但在本地工作

[英]Upload file to s3 with PHP on a EC2 instance throw credentials error, but works locally

I have tested my function to upload images to s3 on my machine, but when I go to production on ec2, by a strange reason, it doesn't work.我已经在我的机器上测试了将图像上传到 s3 的功能,但是当我在 ec2 上进行生产时,由于一个奇怪的原因,它不起作用。

This is the error:这是错误:

CredentialsException in InstanceProfileProvider.php line 79:Error retrieving credentials from the instance profile metadata server. (Client error: 404)

This is the code:这是代码:

$destinationPath = 'images/institutions/logos';
    $extension = $data['int_logo']->getClientOriginalExtension();
    $keyname = $destinationPath.'/'.$username.'.'.$extension;
    $bucket = "*****";
    $filepath = $data['int_logo'];

    $s3 = new S3Client([
        'region'  => 'us-west-2',
        'version' => '2006-03-01',
        'scheme' => 'http'
    ]);

    $result = $s3->putObject(array(
        'Bucket'       => $bucket,
        'Key'          => $keyname,
        'SourceFile'   => $filepath,
        'ACL'          => 'public-read'
    ));

    return $result['ObjectURL'];
}

And this is my s3 policy:这是我的 s3 政策:

{
"Version": "2012-10-17",
"Id": "*******",
"Statement": [
    {
        "Sid": "******",
        "Effect": "Allow",
        "Principal": "*",
        "Action": [
            "s3:GetObject",
            "s3:PutObjectAcl",
            "s3:PutObject"
        ],
        "Resource": "arn:aws:s3:::****/*"
    }
]}

I don't know why it throw an error with the credentials, I'm not using any authentication, everyone can put a file on this bucket.我不知道为什么它会抛出凭据错误,我没有使用任何身份验证,每个人都可以在这个存储桶上放一个文件。 And it works 100% on my machine.它在我的机器上 100% 工作。

Solution to establish an anonymous connection:建立匿名连接的解决方法:

Change:改变:

    $s3 = new S3Client([
        'region'  => 'us-west-2',
        'version' => '2006-03-01',
        'scheme' => 'http',
    ]);

To:到:

    $s3 = new S3Client([
        'region'  => 'us-west-2',
        'version' => '2006-03-01',
        'scheme' => 'http',
        'credentials' => false
    ]);

I still don't know why my local machine can establish the connection, but the ec2 server can't do it without this line.我还是不知道为什么我的本地机器可以建立连接,但是没有这条线,ec2服务器就做不到。

I have had the same problem in the past.我过去也遇到过同样的问题。 I ended up having to put the following code in, that worked for me:我最终不得不放入以下代码,这对我有用:

$s3->path_style = true;

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM