Working with AWS S3 using PHP: Uploads, Downloads, and Basic CRUD Operations

AWS S3 (Simple Storage Service) provides a scalable and reliable object storage solution. Here’s an overview of using AWS S3 with PHP, including sample code snippets, commands, and expected outputs.

Prerequisites:

  • An AWS account with S3 enabled.
  • PHP environment with the AWS SDK for PHP installed. You can install it using Composer:
composer require aws/aws-sdk-php
  • Basic understanding of PHP and AWS concepts.

1. Uploading a File to S3:

Here’s a code example demonstrating how to upload a file to an S3 bucket:

<?php

require 'vendor/autoload.php';

use Aws\S3\S3Client;
use Aws\Exception\AwsException;

// Replace with your AWS credentials and bucket name
$credentials = [
    'key' => 'your_access_key_id',
    'secret' => 'your_secret_access_key',
];
$bucketName = 'your-bucket-name';
$filePath = 'path/to/your/file.txt';
$key = 'uploads/my-file.txt'; // Key under which the file will be stored in S3

$s3Client = new S3Client($credentials);

try {
  $result = $s3Client->putObject([
      'Bucket' => $bucketName,
      'Key' => $key,
      'Body' => fopen($filePath, 'r'),
  ]);
  
  // Handle successful upload
  echo "File uploaded successfully. Object URL: " . $result['ObjectURL'];
} catch (AwsException $e) {
  // Handle upload error
  echo "Error uploading file: " . $e->getMessage();
}

Explanation:

  1. The code requires the AWS SDK for PHP (vendor/autoload.php).
  2. It defines your AWS credentials, bucket name, file path, and the desired key under which the file will be stored in S3.
  3. An S3Client object is created using your credentials.
  4. The putObject method uploads the file to the specified bucket with the provided key. The Body parameter uses fopen to read the file contents.
  5. The code handles a successful upload by echoing the object URL, which can be used to access the file in S3.
  6. An error handling block catches any exceptions during the upload process.

Expected Output (Success):

File uploaded successfully. Object URL: https://your-bucket-name.s3.amazonaws.com/uploads/my-file.txt

2. Downloading a File from S3:

See also  Organizing Front-end UI for PHP

Here’s how to download a file from S3:

<?php

require 'vendor/autoload.php';

use Aws\S3\S3Client;
use Aws\Exception\AwsException;

// Replace with your AWS credentials, bucket name, and object key
$credentials = [
    'key' => 'your_access_key_id',
    'secret' => 'your_secret_access_key',
];
$bucketName = 'your-bucket-name';
$key = 'uploads/my-file.txt';
$downloadPath = 'downloads/my-file.txt'; // Local path where the file will be downloaded

$s3Client = new S3Client($credentials);

try {
  $result = $s3Client->getObject([
      'Bucket' => $bucketName,
      'Key' => $key,
  ]);
  
  // Save downloaded content to a local file
  $result['Body']->saveAs($downloadPath);
  echo "File downloaded successfully to: $downloadPath";
} catch (AwsException $e) {
  // Handle download error
  echo "Error downloading file: "  . $e->getMessage();
}

Explanation:

  1. Similar to the upload example, the code requires the AWS SDK and defines AWS credentials, bucket name, and object key.
  2. It also defines the local path where the downloaded file will be saved.
  3. The getObject method retrieves the file from S3.
  4. The saveAs method of the response body ($result['Body']) saves the downloaded content to the specified local path.
  5. The code displays a success message with the download location.
  6. Error handling captures any exceptions during the download process.

Expected Output (Success):

File downloaded successfully to: downloads/my-file.txt

Comments

No comments yet. Why don’t you start the discussion?

Leave a Reply

Your email address will not be published. Required fields are marked *

This site uses Akismet to reduce spam. Learn how your comment data is processed.