Connect to S4 with PHP
Uses the AWS SDK for PHP 3.x. The code below can be placed in a single file and run in order; move the use statements to the top of the file.
Prerequisites
- Create a bucket in the console;
- Create a sub-user and AccessKey, and grant the sub-user access to this bucket. A new sub-user has no permissions;
- Put the keys in environment variables instead of writing them in code:
export S4_ACCESS_KEY="Sub-user AccessKey"
export S4_SECRET_KEY="Sub-user SecretKey"Install
composer require aws/aws-sdk-phpThe examples on this page were tested on PHP 8.2 and aws/aws-sdk-php 3.x.
Connect to S4
require 'vendor/autoload.php';
use Aws\S3\S3Client;
$s3 = new S3Client([
'version' => 'latest',
'endpoint' => 'https://s3.bitiful.net',
'region' => 'cn-east-1',
'credentials' => [
'key' => getenv('S4_ACCESS_KEY'),
'secret' => getenv('S4_SECRET_KEY'),
],
'use_aws_shared_config_files' => false,
]);
$bucket = 'my-bucket';use_aws_shared_config_files is set to false to avoid interference from other AWS configuration on the server.
Upload files
An object with the same name is overwritten directly. If ContentType is left empty, S4 detects it automatically.
// Upload a text string
$s3->putObject([
'Bucket' => $bucket,
'Key' => 'docs/hello.txt',
'Body' => '你好,S4',
'ContentType' => 'text/plain; charset=utf-8',
]);
// Upload a local file, setting cache time and custom metadata
$s3->putObject([
'Bucket' => $bucket,
'Key' => 'images/photo.jpg',
'SourceFile' => 'photo.jpg',
'ContentType' => 'image/jpeg',
'CacheControl' => 'max-age=86400',
'Metadata' => ['author' => 'bitiful'],
]);Upload large files
Use multipart upload for files larger than 100 MB: parts can upload concurrently, and a failed part is the only one you need to retry. Each part is 5 MiB to 20 GiB, with up to 10000 parts.
use Aws\Exception\MultipartUploadException;
use Aws\S3\MultipartUploader;
$uploader = new MultipartUploader($s3, 'video.mp4', [
'bucket' => $bucket,
'key' => 'videos/video.mp4',
'part_size' => 16 * 1024 * 1024, // 16 MiB per part
'concurrency' => 4, // 4 parts uploaded at a time
'before_initiate' => function ($command) {
$command['ContentType'] = 'video/mp4';
},
]);
// On failure, resume from the breakpoint, retrying up to 3 times
for ($i = 0; $i < 3; $i++) {
try {
$result = $uploader->upload();
echo $result['ETag'], PHP_EOL;
break;
} catch (MultipartUploadException $e) {
$uploader = new MultipartUploader($s3, 'video.mp4', ['state' => $e->getState()]);
}
}Download files
Download private files with your secret key. To read only part of a file, use Range instead of downloading the whole file.
// Read as a string
echo $s3->getObject(['Bucket' => $bucket, 'Key' => 'docs/hello.txt'])['Body'], PHP_EOL;
// Save to a file
$s3->getObject([
'Bucket' => $bucket,
'Key' => 'videos/video.mp4',
'SaveAs' => 'video-copy.mp4',
]);
// Read only the first 1 KiB
$part = $s3->getObject([
'Bucket' => $bucket,
'Key' => 'videos/video.mp4',
'Range' => 'bytes=0-1023',
]);
echo $part['ContentRange'], PHP_EOL;List files
Each page returns 100 entries by default and 1000 at most; always use a paginator to page through results. Delimiter supports only /.
// List all objects under a prefix, paging automatically
$pages = $s3->getPaginator('ListObjectsV2', ['Bucket' => $bucket, 'Prefix' => 'images/']);
foreach ($pages as $page) {
foreach ($page['Contents'] ?? [] as $obj) {
echo $obj['Key'], ' ', $obj['Size'], ' ', $obj['LastModified'], PHP_EOL;
}
}
// List only the top-level directories
$root = $s3->listObjectsV2(['Bucket' => $bucket, 'Delimiter' => '/']);
foreach ($root['CommonPrefixes'] ?? [] as $p) {
echo 'Directory ', $p['Prefix'], PHP_EOL;
}Get file information
Retrieve metadata without downloading the content. You can also use this to check whether an object exists.
$info = $s3->headObject(['Bucket' => $bucket, 'Key' => 'images/photo.jpg']);
echo $info['ContentType'], ' ', $info['ContentLength'], ' ', $info['Metadata']['author'], PHP_EOL;
// Check whether it exists
var_dump($s3->doesObjectExistV2($bucket, 'images/none.jpg'));Copy and move
Copying is done server-side, so data does not pass through your machine. Move is an S4 extension: append ?move=true to CopySource. It only changes the location without copying data, regardless of file size. See Move and rename objects.
// The object key in CopySource must be URL-encoded, keeping /
function copySource(string $bucket, string $key): string
{
return $bucket . '/' . implode('/', array_map('rawurlencode', explode('/', $key)));
}
// Copy
$s3->copyObject([
'Bucket' => $bucket,
'Key' => 'images/photo-copy.jpg',
'CopySource' => copySource($bucket, 'images/photo.jpg'),
]);// Move / rename: S4 extension, no data copied
$s3->copyObject([
'Bucket' => $bucket,
'Key' => 'archive/photo.jpg',
'CopySource' => copySource($bucket, 'images/photo-copy.jpg') . '?move=true',
]);Delete files
Deleted objects cannot be recovered. A batch delete handles up to 1000 keys at a time; if you lack write permission on any one key, the whole batch returns 403.
// Delete one object
$s3->deleteObject(['Bucket' => $bucket, 'Key' => 'docs/hello.txt']);
// Batch delete, up to 1000 objects at a time
$keys = ['images/a.jpg', 'images/b.jpg'];
$result = $s3->deleteObjects([
'Bucket' => $bucket,
'Delete' => [
'Objects' => array_map(fn ($k) => ['Key' => $k], $keys),
'Quiet' => true,
],
]);
foreach ($result['Errors'] ?? [] as $e) {
echo $e['Key'], ' ', $e['Code'], ' ', $e['Message'], PHP_EOL;
}Presigned URLs
A presigned URL embeds the authorization in the link, so the holder can upload or download without a secret key. It is valid for up to 7 days. If you sign Content-Type for an upload, the client must send exactly the same value.
// Download URL, valid for 1 hour, with a specified file name
$cmd = $s3->getCommand('GetObject', [
'Bucket' => $bucket,
'Key' => 'images/photo.jpg',
'ResponseContentDisposition' => 'attachment; filename="photo.jpg"',
]);
$getUrl = (string) $s3->createPresignedRequest($cmd, '+1 hour')->getUri();
echo $getUrl, PHP_EOL;
// Upload URL, valid for 10 minutes; the client sends a PUT to it
$cmd = $s3->getCommand('PutObject', ['Bucket' => $bucket, 'Key' => 'uploads/avatar.jpg']);
$putUrl = (string) $s3->createPresignedRequest($cmd, '+10 minutes')->getUri();
echo $putUrl, PHP_EOL;Presigned URLs with extension parameters
Extension parameters such as CoreIX processing parameters, rate limits, and request limits must be added before signing. Appending them after signing returns SignatureDoesNotMatch.
use Aws\CommandInterface;
use Aws\Middleware;
use Psr\Http\Message\RequestInterface;
// Generate a presigned URL with S4 extension parameters; they are included in the signature
function presignWith(S3Client $s3, CommandInterface $cmd, array $extra, string $expires = '+1 hour'): string
{
$cmd->getHandlerList()->appendBuild(
Middleware::mapRequest(function (RequestInterface $request) use ($extra) {
$query = http_build_query($extra, '', '&', PHP_QUERY_RFC3986);
$old = $request->getUri()->getQuery();
return $request->withUri(
$request->getUri()->withQuery($old === '' ? $query : $old . '&' . $query)
);
}),
'add-s4-query'
);
return (string) $s3->createPresignedRequest($cmd, $expires)->getUri();
}
$target = ['Bucket' => $bucket, 'Key' => 'images/photo.jpg'];
$url = presignWith($s3, $s3->getCommand('GetObject', $target), [
'w' => '500', // CoreIX: width 500 px
'fmt' => 'webp', // CoreIX: convert to WebP
'x-bitiful-limit-rate' => '1048576', // Per-connection rate limit of 1 MiB/s
'x-bitiful-max-requests' => '3', // At most 3 accesses
]);
echo $url, PHP_EOL;Conditional writes
Conditional writes prevent concurrent overwrites. When the condition is not met, S4 returns 412. See Conditional requests.
try {
// Write only if the object does not exist, to prevent overwriting
$s3->putObject(['Bucket' => $bucket, 'Key' => 'locks/job', 'Body' => 'me', 'IfNoneMatch' => '*']);
} catch (AwsException $e) {
if ($e->getStatusCode() !== 412) {
throw $e;
}
echo 'Object already exists', PHP_EOL;
}Handle errors
For the meaning of each error code, see Error codes and troubleshooting. Rate limiting returns 429 TooManyRequest; catch it and retry with backoff.
use Aws\Exception\AwsException;
try {
$s3->getObject(['Bucket' => $bucket, 'Key' => 'not-exists.txt']);
} catch (AwsException $e) {
if ($e->getAwsErrorCode() === 'NoSuchKey') {
echo 'Object does not exist', PHP_EOL;
} else {
echo $e->getStatusCode(), ' ', $e->getAwsErrorCode(), ' ', $e->getAwsErrorMessage(), PHP_EOL;
}
}FAQ
How do I configure Laravel
In the s3 disk in config/filesystems.php, set endpoint to https://s3.bitiful.net, region to cn-east-1, and use_path_style_endpoint to false, and fill in the keys and bucket name.
Returns 403 AccessDenied
The sub-user has no permission on this bucket or directory. See Sub-user permissions. Creating and deleting buckets can only be done in the console.
Returns SignatureDoesNotMatch
The key was copied incorrectly, or the presigned URL was modified after signing. Extension parameters must be added before signing. See the checklist.
Download speed is low
Direct S4 connections have a per-connection rate limit. Download large files in segments over multiple threads, and use a CDN to serve visitors.
Related documentation
Full reference for request limits, rate limits, Simul-Transfer, and other parameters.
Checklists for 403, SignatureDoesNotMatch, and other issues.
Support status and differences for each operation.
Recommended practices for direct uploads from browsers and apps.