Using AWS S3 with PHP: Installation, Client Setup, Bucket Operations, Object Management, Presigned URLs, Compression, and CORS Configuration
This guide explains how to install the AWS SDK for PHP, configure an S3 client, perform bucket and object operations, paginate and filter objects, generate presigned URLs, compress downloaded objects with ZipArchive, and set up CORS for AWS S3 buckets.
AWS Simple Storage Service (S3) is a highly scalable object storage service that lets you store and retrieve any amount of data from anywhere on the internet. Objects are stored in containers called buckets, and the SDK provides methods to create, read, update, and delete them.
Install the AWS SDK for PHP
Ensure your environment has PHP 5.3.3+ with the cURL extension and Composer installed. Use Composer to add the SDK:
<code>composer require aws/aws-sdk-php</code>Include the Composer autoloader in your project:
<code>require 'vendor/autoload.php';</code>Set Up the S3 Client
Initialize the client with your AWS credentials:
<code>// Use your AWS credentials to set up the S3 client
$client = new S3Client([
'version' => 'latest',
'region' => 'us-east-1',
'credentials' => [
'key' => AWS_KEY,
'secret' => AWS_SECRET,
],
]);</code>Bucket Operations
Create a bucket:
<code>$client->createBucket(['Bucket' => $bucketName]);</code>Upload an object to a bucket:
<code>$client->putObject([
'Bucket' => $bucketName,
'Key' => $objectKey,
'Body' => $objectContent,
]);</code>List all buckets associated with the client:
<code>$buckets = $client->listBuckets();
// $buckets is an array of bucket names and creation dates</code>Object Pagination, Filtering, and Selection
Use listObjectsV2() to paginate and filter objects. Required Bucket parameter specifies the target bucket.
<code>$listObjectsParams = [
'Bucket' => 'YOUR_BUCKET_NAME',
];
$objects = $client->listObjectsV2($listObjectsParams);
</code>Optional parameters such as Delimiter , Prefix , StartAfter , and MaxKeys can refine the results:
<code>$listObjectsParams['Delimiter'] = '/';
$listObjectsParams['Prefix'] = '/GENRE_FOLDER/2026';
$listObjectsParams['StartAfter']= '/GENRE_FOLDER/2026/GENRE_SONG_2.mp3';
$listObjectsParams['MaxKeys'] = '20';
</code>The response includes Contents , CommonPrefixes , and pagination flags.
Generate Presigned URLs
Presigned URLs grant time‑limited access to objects. Example function to create a download URL for a single object:
<code>function getObjectDownloadURL($client, $bucketName, $objectKey, $objectName)
{
$cmd = $client->getCommand('GetObject', [
'Bucket' => $bucketName,
'Key' => $objectKey,
'ResponseContentDisposition' => urlencode("attachment; filename=$objectName"),
]);
$request = $client->createPresignedRequest($cmd, '+7 days');
return (string) $request->getUri();
}
</code>A helper can generate URLs for multiple objects with optional text and max‑key filters.
Compress S3 Objects with ZipArchive
Download presigned URLs and add them to a zip file using PHP's ZipArchive class:
<code>function downloadAndCompressUrls($urls, $zipFileName)
{
$zip = new ZipArchive();
if ($zip->open($zipFileName, ZipArchive::CREATE | ZipArchive::OVERWRITE) !== true) {
return null;
}
foreach ($urls as $url) {
$fileContent = @file_get_contents($url[0]);
if ($fileContent !== false) {
$zip->addFromString(basename($url[1]), $fileContent);
}
}
$zip->close();
return $zipFileName;
}
</code>Configure CORS for an S3 Bucket
CORS allows web applications from other domains to access bucket resources. Example CORS configuration JSON:
<code>{
"CORSRules": [
{
"AllowedHeaders": ["*"],
"AllowedMethods": ["GET"],
"AllowedOrigins": ["https://localhost:8000"]
}
]
}
</code>Apply this configuration to control which origins can perform which HTTP methods on your S3 resources.
php中文网 Courses
php中文网's platform for the latest courses and technical articles, helping PHP learners advance quickly.
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.