Working with S3 and Cloud Storage in PHP
Cloud object storage compatible with the Amazon S3 (Simple Storage Service) protocol has become the de facto standard for storing files, images, backups, and static content. PHP provides powerful tools for integrating with storage services such as AWS S3, MinIO (self-hosted), DigitalOcean Spaces, Wasabi, Yandex Object Storage, and others. In this article, we will take a detailed look at how to work with S3-compatible storage in PHP using the official AWS SDK and alternative libraries.
Basic S3 Concepts
Before diving into the code, it is important to understand the key concepts of S3:
- Bucket — a container for objects (files). The bucket name must be globally unique (for public clouds).
- Object — a file and its metadata. Each object has a Key — the path to the file within the bucket.
- Region — the geographical location of the storage.
- Credentials — the Access Key ID and Secret Access Key for authentication.
- Endpoint — the storage URL (required for S3-compatible services other than AWS).
Installing the AWS SDK for PHP
The official library for working with S3 is aws/aws-sdk-php. Installation via Composer:
composer require aws/aws-sdk-phpNo additional dependencies are required for working with MinIO or DigitalOcean Spaces — the SDK supports custom endpoints.
Basic S3 Client Configuration
Let's create a client to connect to AWS S3:
<?phprequire 'vendor/autoload.php';
use Aws\\S3\\S3Client;use Aws\\Exception\\AwsException;
$s3Client = new S3Client([ 'version' => 'latest', 'region' => 'us-east-1', 'credentials' => [ 'key' => 'YOUR_ACCESS_KEY', 'secret' => 'YOUR_SECRET_KEY', ],]);?>For MinIO (a local S3-compatible storage), the configuration will look like this:
<?php$s3Client = new S3Client([ 'version' => 'latest', 'region' => 'us-east-1', // MinIO ignores the region 'endpoint' => 'http://localhost:9000', 'use_path_style_endpoint' => true, 'credentials' => [ 'key' => 'minioadmin', 'secret' => 'minioadmin', ],]);?>Note the use_path_style_endpoint parameter — it is necessary for MinIO and some non-AWS storage services.
Bucket Management
Creating a Bucket
<?phptry { $result = $s3Client->createBucket([ 'Bucket' => 'my-php-bucket', ]); echo "Bucket created: " . $result['Location'];} catch (AwsException $e) { echo "Error: " . $e->getMessage();}?>Checking if a Bucket Exists
<?php$exists = $s3Client->doesBucketExist('my-php-bucket');if ($exists) { echo "Bucket exists";} else { echo "Bucket not found";}?>Listing All Buckets
<?php$buckets = $s3Client->listBuckets();foreach ($buckets['Buckets'] as $bucket) { echo $bucket['Name'] . " (created: " . $bucket['CreationDate'] . ")<br>";}?>Uploading Files to S3
Uploading from a String (Text Data)
<?phptry { $result = $s3Client->putObject([ 'Bucket' => 'my-php-bucket', 'Key' => 'hello.txt', 'Body' => 'Hello, S3 from PHP!', ]); echo "File uploaded. URL: " . $result['ObjectURL'];} catch (AwsException $e) { echo "Upload error: "