Home > Software design >  can't push file to s3 buket in php
can't push file to s3 buket in php

Time:12-02

I took the sample code from the aws documentation, and I always get this error : IncalculablePayloadException

<?php $filepath = (isset($_SERVER['HTTPS']) && $_SERVER['HTTPS'] === 'on' ? "https" : "http") . "://$_SERVER[HTTP_HOST]";
    
    
    require 'aws.phar';
    
    use Aws\S3\S3Client;
    use Aws\S3\Exception\S3Exception;
    
    $s3Key = 'mykey';
    $s3Secret = 'mysecretkey';
    $region = 'eu-west-3';
    $s3Bucket = 'mybucket';
    
    
    $bucket = $s3Bucket;
    $file_Path = $filepath.'/msk.png';
    $key = basename($filepath);
    echo $file_Path;
    try {
        //Create a S3Client
        $s3Client = new S3Client([
            'profile' => 'default',
            'region' => $region,
            'version' => '2006-03-01',
            // 'debug'   => true
        ]);
        $result = $s3Client->putObject([
            'Bucket' => $bucket,
            'Key' => $key,
            'SourceFile' => $file_Path,
        ]);
    } catch (S3Exception $e) {
        echo $e->getMessage() . "\n";
    }

I have checked that my file exist, the path is correct. I have no idea what to do, this should work, it's from their damned doc. I have tried with other files, different code found else where but I always get the same error. Thanks for the help.

EDIT --------- 1 I have change $file_Path to $file_Path = 'msk.png'; And it's now 'working'. It upload a file to S3, but not a png but an xml file. with at the end

<Code>AccessDenied</Code>
<Message>Access Denied</Message>

Any idea why? EDIT --------- 2 Ok, so now I know why, the permission of the file was not set to read for public access. How can i set the ACL with putObject ?

CodePudding user response:

The AWS PHP SDK Documentation has this description of SourcePath:

The path to a file on disk to use instead of the Body parameter.

But you are not providing a file on disk, you are providing a URL.

You have two options:

  • Provide the disk location of the path, based on where it is on your server. For instance, using __DIR__ to refer to the directory of the current PHP file, it might be $file_Path = __DIR__ . '/../public/msk.png';
  • Download the content first, and pass it in as a string to the Body parameter instead of SourcePath, e.g. using $body = file_get_contents($File_Path);

The first option makes more sense if it's a file on your own server, but the second one might be useful if you've simplified the example.

  • Related