【问题标题】:How do you display image from Amazon S3 with PHP?如何使用 PHP 显示来自 Amazon S3 的图像?
【发布时间】:2021-11-23 16:14:45
【问题描述】:

您好,我正在使用原生 PHP(7.3.29) 创建图片发布网站,并使用 heroku 部署它,但 heroku 不允许显示图像。 所以我使用了 Amazon S3 并上传了图片,它可以正常工作,但我不知道如何在 index.php 上显示来自 S3 的图片?

我尝试查找如何使用 PHP 显示来自 Amazon S3 的图像,但大多数文章都是关于 Laravel 的,所以如果你能帮助我,我真的很感激!

谢谢!

这是我的代码...

add_post.php

if(isset($_POST['create_post'])){
    
    if(!empty($_POST['post_contents'])){
    
    if(isset($_FILES['image'])){
    $file_name = $_FILES['image']['name'];   
    $temp_file_location = $_FILES['image']['tmp_name']; 

    $s3 = new Aws\S3\S3Client([
        'region'  => 'ap-northeast-1',
        'version' => 'latest',
        'credentials' => [
            'key'    => "************",
            'secret' => "************",
        ]
    ]);     

    $result = $s3->putObject([
        'Bucket' => '********',
        'Key'    => $file_name,
        'SourceFile' => $temp_file_location         
    ]);
    
    $path = $result['ObjectURL'];

}

    $post = $db->prepare('INSERT INTO posts SET post_user_id=?, post_contents=?, post_image=?, post_date=NOW()');
    $post->execute(array(
        $user['user_id'],
        $_POST['post_contents'],
        $file_name = date('YmdHis'),
        ));
        
    header('Location: index.php');
    exit();
}else{
    echo "<script>alert('Contents fields cannot be empty')</script>";
}
}

index.php

<?php foreach ($posts as $post): ?>
<div class="post-preview">
      <a href="post.php?post_id=<?php echo htmlspecialchars($post['post_id']); ?>"><?php echo htmlspecialchars($post['post_contents']); ?></a>
      <p><img width='300' src="images/<?php echo htmlspecialchars($post['post_image'], ENT_QUOTES); ?>"; ?></p>
      <p class="postContents"><?php echo htmlspecialchars($post['post_date'], ENT_QUOTES); ?> | <?php echo htmlspecialchars($post['user_name'], ENT_QUOTES); ?></p>
  <hr class="my-4" />
</div>
<?php endforeach; ?>

【问题讨论】:

  • 您是否可以访问您存储在 S3 中的对象的 URL
  • 嗨@Lucasz 哎呀我没有检查它......现在我检查了它我无法访问对象的URL......我收到了这个错误......这个XML 文件似乎没有任何与之关联的样式信息。文档树如下所示。 &lt;Error&gt; &lt;Code&gt;AccessDenied&lt;/Code&gt; &lt;Message&gt;Access Denied&lt;/Message&gt; &lt;RequestId&gt;VK6HN5DTHZ64CXY7&lt;/RequestId&gt; &lt;HostId&gt;Gb6cyjmkS/V9y8cWSPsWBXWy7ryT99qr5o6gzS3aQbaAXvYuzNHqk4Hf/VVLhwcJ977F6iVZ0EY=&lt;/HostId&gt; &lt;/Error&gt;
  • 如果图像被允许公开,您可以在您的存储桶中将它们公开。 aws.amazon.com/premiumsupport/knowledge-center/…

标签: php amazon-web-services amazon-s3 heroku


【解决方案1】:

要从您的存储桶中检索对象,您应该公开这些对象。我不建议您公开访问整个存储桶。

最佳做法是创建预签名 URL 来获取它们。

https://docs.aws.amazon.com/AmazonS3/latest/userguide/ShareObjectPreSignedURL.html

【讨论】:

    猜你喜欢
    • 2013-11-21
    • 2015-09-16
    • 2011-01-18
    • 2015-04-26
    • 2018-08-05
    • 2015-03-02
    • 2020-01-08
    • 2011-06-22
    • 1970-01-01
    相关资源
    最近更新 更多