# Connect to S4 with PHP

> Connect to Bitiful S4 with the AWS SDK for PHP: complete examples for uploads, resumable multipart uploads, downloads, listing, presigned URLs, extension parameters, and error handling.

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

1. [Create a bucket](https://docs.bitiful.com/en/bitiful-s4/handbook/buckets.md) in the console;
2. [Create a sub-user and AccessKey](https://docs.bitiful.com/en/bitiful-s4/handbook/access-keys.md), and [grant the sub-user access to this bucket](https://docs.bitiful.com/en/bitiful-s4/handbook/permissions.md). A new sub-user has no permissions;
3. Put the keys in environment variables instead of writing them in code:

```bash
export S4_ACCESS_KEY="Sub-user AccessKey"
export S4_SECRET_KEY="Sub-user SecretKey"
```

## Install

```bash
composer require aws/aws-sdk-php
```

The examples on this page were tested on PHP 8.2 and aws/aws-sdk-php 3.x.

## Connect to S4

```php title="s4.php"
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](https://docs.bitiful.com/en/best-practice/auto-detect-mime.md).

```php title="s4.php"
// 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.

```php title="s4.php"
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.

```php title="s4.php"
// 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 `/`.

```php title="s4.php"
// 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.

```php title="s4.php"
$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](https://docs.bitiful.com/en/bitiful-s4/features/move-object.md).

```php title="s4.php"
// 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'),
]);
```

```php title="s4.php"
// 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.

```php title="s4.php"
// 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.

```php title="s4.php"
// 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](https://docs.bitiful.com/en/coreix/basic.md), rate limits, and request limits must be added **before signing**. Appending them after signing returns `SignatureDoesNotMatch`.

```php title="s4.php"
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](https://docs.bitiful.com/en/developer/s3/conditional-requests.md).

```php title="s4.php"
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](https://docs.bitiful.com/en/developer/s3/errors.md). Rate limiting returns 429 `TooManyRequest`; catch it and retry with backoff.

```php title="s4.php"
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

<details>
<summary>How do I configure Laravel</summary>

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.

</details>

<details>
<summary>Returns 403 AccessDenied</summary>

The sub-user has no permission on this bucket or directory. See [Sub-user permissions](https://docs.bitiful.com/en/bitiful-s4/handbook/permissions.md). Creating and deleting buckets can only be done in the console.

</details>

<details>
<summary>Returns SignatureDoesNotMatch</summary>

The key was copied incorrectly, or the presigned URL was modified after signing. Extension parameters must be added before signing. See the [checklist](https://docs.bitiful.com/en/developer/s3/errors.md).

</details>

<details>
<summary>Download speed is low</summary>

Direct S4 connections have a per-connection rate limit. Download large files in segments over multiple threads, and use a [CDN](https://docs.bitiful.com/en/cdn/intro.md) to serve visitors.

</details>

## Related documentation

[**Presigned URLs and extensions**](https://docs.bitiful.com/en/developer/s3/presigned-url.md)

Full reference for request limits, rate limits, Simul-Transfer, and other parameters.

[**Error codes and troubleshooting**](https://docs.bitiful.com/en/developer/s3/errors.md)

Checklists for 403, SignatureDoesNotMatch, and other issues.

[**S3 API compatibility**](https://docs.bitiful.com/en/developer/s3/compatibility.md)

Support status and differences for each operation.

[**Upload files securely from the client**](https://docs.bitiful.com/en/best-practice/web-uploads.md)

Recommended practices for direct uploads from browsers and apps.
