AWS PHP SDK v3检查S3存储桶中是否已存在文件

时间:2019-06-28 12:09:38

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

我正在使用PHP和AWS开发工具包v3开发一个项目,其中我必须通过传递文件名来检查文件是否已经存在。

这是我尝试过的:

来自 HTML模板:

<html>
    <form id="form" action="check_existing.php" method="post">
        <input type="text" name="fName" >
        <input type="submit" name="submit" value="Submit"><br />
    </form>
</html>

来自 check_existing.php:

include 'create_client.php';
if(isset($_POST["submit"])){            
    $filename = $_POST['fName'];
    $info = $s3->doesObjectExist($bucketName, $filename);
    print($info);
    if ($info)
    {
        echo 'File exists';
    }
    else
    {
    echo 'File does not exists';
    }
}

这是我创建s3客户端的方法:

$s3 = new Aws\S3\S3Client([
    'region' => $region,
    'version' => 'latest',
    'credentials' => [
        'key'    => $IAM_KEY,
        'secret' => $IAM_SECRET,
    ],
]);
  

问题:它始终返回File does not exists

2 个答案:

答案 0 :(得分:0)

$s3 = new S3($s3_accesskey, $s3_secretkey); //create s3 object

$info = $s3->getObjectInfo($s3_bucket, $filename); // $filename can be path of file in bucket
if ($info){
    echo 'File exists';
}else{
    echo 'File does not exists';
}

getObjectInfo()返回如下信息

Array
(
[date] => 1596690179
[time] => 1596651169
[hash] => 1234c1234341a7f2565c108b23b4aaca
[type] => image/jpeg
[size] => 18968
)

答案 1 :(得分:-1)

您可以尝试一下。 ref:enter link description here

$s3 = new AmazonS3();
$bucket = 'your-bucket' . strtolower($s3->key);

$test = $s3->doesObjectExist($bucket, 'testfile.jpg');

// Success or not? (Boolean, not a CFResponse object)
var_dump($test); // it will return boolean