简体   繁体   中英

How do you display image from Amazon S3 with PHP?

Hi I am creating picture posting website with native PHP(7.3.29) and I deployed it with heroku but heroku is not allow to display images. So I used Amazon S3 and I uploaded image and it worked but I have no idea how can I display images from S3 on index.php?

I tried to look up how to display image from Amazon S3 with PHP but most articles are about Laravel so if you can help me I really appreciate it!

Thank you!

Here are my codes...

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

To retrieve the objects from your bucket you should make the objects public. I do not recommend making your whole bucket publicly accessible.

Best practice is to create presigned URL to get them.

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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