Sample code for 30+ languages & platforms
PHP ActiveX Requires Chilkat v11.6.0+

S3 Http: Multipart Upload with Checksums and Checkpoint

See more S3 - HTTP Examples

Uses Chilkat.Http with Amazon S3 general purpose buckets and Signature Version 4. These examples do not cover directory buckets/S3 Express, access-point ARNs, Outposts, or other specialized endpoints. They target the commercial AWS partition; other partitions need their documented endpoint suffix.

Load private qa_data/aws/s3.json containing nonempty string fields access_key and secret_key, plus session_token for temporary credentials. Prefer short-lived role credentials. These samples do not discover AWS profiles or refresh credentials. Set the bucket's actual region and replace sample bucket names and object keys. TLS certificate verification is explicitly enabled. Keep detailed HTTP diagnostics private because they can contain credentials or presigned URLs.

Uses explicit signed Http requests to preserve query parameters, conditional headers, and full responses. The included SigV4 block signs the exact path, sorted encoded query and headers used by this example; it is not a general-purpose HTTP signing library. Keep the clock accurate and do not change signed data after signing. Code requires Chilkat 11.6.0 or later; locally tested with 11.8.0.

Uses a private checkpoint directory for one upload and an immutable source file. Run one process per checkpoint; never run upload/resume concurrently with abort. The fixed 8 MiB part size limits this demonstration to nonempty files of at most 10,000 parts (78.125 GiB). It does not impose that limit on S3 itself; choose larger valid part sizes for larger objects.

Uses SHA-256 COMPOSITE multipart checksums, validates part checksums, and verifies the returned composite checksum. ETags are retained for completion but never treated as MD5. Completion can return an error inside HTTP 200; the XML result is checked. Source identity is SHA-256, not just filename/length. The checkpoint contains no AWS credentials.

Requires s3:PutObject, s3:ListMultipartUploadParts for resume, and s3:GetObject for uncertain-completion recovery, plus relevant KMS permissions if bucket defaults use KMS. Incomplete parts incur storage charges until completed or aborted. Configure a suitable incomplete-multipart lifecycle rule as an operational safeguard. Timeout during initiation may leave an upload without a checkpoint; list uploads and investigate before initiating another.

Starts, transfers and completes one upload. Saves state before parts and a pending completion record before completion. Run the resume companion after interruptions; do not rerun start against an existing cache. Metadata binds an uncertain completion to a random upload identity.

AWS reference

Chilkat PHP ActiveX Downloads

PHP ActiveX
<?php

$success = 0;

$stringCompare = new COM("Chilkat.StringBuilder");
//  This example requires the Chilkat API to have been previously unlocked.
//  See Global Unlock Sample for sample code.
//  Load private credentials; never put access keys or session tokens in source.
$credentials = new COM("Chilkat.JsonObject");
$credentials->Strict = 1;
$success = $credentials->LoadFile('qa_data/aws/s3.json');
if ($success != 1) {
    print 'Could not load private S3 credentials.' . "\n";
    exit;
}

$stringCompare->SetString($credentials->stringOf('access_key'));
$stringMatch1 = $stringCompare->ContentsEqual('',1);
if (($credentials->JsonTypeOf('access_key') != 1) or ($stringMatch1 == 1)) {
    print 'Missing or invalid access_key.' . "\n";
    exit;
}

$stringCompare->SetString($credentials->stringOf('secret_key'));
$stringMatch2 = $stringCompare->ContentsEqual('',1);
if (($credentials->JsonTypeOf('secret_key') != 1) or ($stringMatch2 == 1)) {
    print 'Missing or invalid secret_key.' . "\n";
    exit;
}

$http = new COM("Chilkat.Http");
$http->AwsAccessKey = $credentials->stringOf('access_key');
$http->AwsSecretKey = $credentials->stringOf('secret_key');
if ($credentials->HasMember('session_token') == 1) {
    $stringCompare->SetString($credentials->stringOf('session_token'));
    $stringMatch3 = $stringCompare->ContentsEqual('',1);
    if (($credentials->JsonTypeOf('session_token') != 1) or ($stringMatch3 == 1)) {
        print 'session_token must be a nonempty string when supplied.' . "\n";
        exit;
    }

    $http->AwsSessionToken = $credentials->stringOf('session_token');
}

//  Current Chilkat uses SigV4 by default. Do not select deprecated SigV2.
//  Set the actual bucket region, not the caller's location.
$region = 'us-west-2';
$http->AwsRegion = $region;
$endpoint = new COM("Chilkat.StringBuilder");
$endpoint->Append('s3.');
$endpoint->Append($region);
$endpoint->Append('.amazonaws.com');
$http->AwsEndpoint = $endpoint->getAsString();
$http->RequireSslCertVerify = 1;
$http->FollowRedirects = 0;
//  A region redirect is not success. Correct the endpoint and signing region.
$bucketName = 'your-bucket-name';
$objectKey = 'examples/archive.bin';
$response = new COM("Chilkat.HttpResponse");
$signer = new COM("Chilkat.Crypt2");
$signer->Charset = 'utf-8';
$signer->HashAlgorithm = 'sha256';
$signer->EncodingMode = 'hexlower';
$signer->MacAlgorithm = 'hmac';
$now = new COM("Chilkat.CkDateTime");
$timestamp = new COM("Chilkat.StringBuilder");
$canonical = new COM("Chilkat.StringBuilder");
$canonicalHeaders = new COM("Chilkat.StringBuilder");
$signedHeaders = new COM("Chilkat.StringBuilder");
$scope = new COM("Chilkat.StringBuilder");
$stringToSign = new COM("Chilkat.StringBuilder");
$signingKey = new COM("Chilkat.StringBuilder");
$authorization = new COM("Chilkat.StringBuilder");
$url = new COM("Chilkat.StringBuilder");
$query = new COM("Chilkat.StringBuilder");
$number = new COM("Chilkat.StringBuilder");
$host = new COM("Chilkat.StringBuilder");
$uri = new COM("Chilkat.StringBuilder");
$xml = new COM("Chilkat.Xml");

$host->Append($bucketName);
$host->Append('.');
$host->Append($endpoint->getAsString());
//  Encode the original key exactly once, preserving S3 path separators.
$uri->SetString($http->urlEncode($objectKey));
$replaceCount = $uri->ReplaceNoCase('%2f','/');
if (($uri->StartsWith('/',1) == 1) or ($uri->Contains('/../',1) == 1) or ($uri->Contains('/./',1) == 1)) {
    print 'Use a key without a leading slash or dot path segments for these examples.' . "\n";
    exit;
}

$uri->Prepend('/');
$files = new COM("Chilkat.FileAccess");
$filePath = 'qa_data/bin/archive.bin';
$fileSize = $files->fileSizeStr($filePath);
if ($files->LastMethodSuccess != 1) {
    print 'Could not read source file size.' . "\n";
    exit;
}

$digest = new COM("Chilkat.Crypt2");
$digest->HashAlgorithm = 'sha256';
$digest->EncodingMode = 'hexlower';
$sourceHash = $digest->hashFileENC($filePath);
if ($digest->LastMethodSuccess != 1) {
    print 'Could not hash source file.' . "\n";
    exit;
}

$digest->EncodingMode = 'base64';
$sourceChecksum = $digest->hashFileENC($filePath);
if ($digest->LastMethodSuccess != 1) {
    print 'Could not compute checksum.' . "\n";
    exit;
}

$cacheDir = 'qa_output/s3-multipart';
$statePath = 'qa_output/s3-multipart/state.json';
$pendingPath = 'qa_output/s3-multipart/completion.json';
$receiptPath = 'qa_output/s3-multipart/completed.json';
$state = new COM("Chilkat.JsonObject");
$state->Strict = 1;
$pending = new COM("Chilkat.JsonObject");
$pending->Strict = 1;

$success = $files->OpenForRead($filePath);
if ($success != 1) {
    print 'Could not open immutable source file.' . "\n";
    exit;
}

$partSize = 8388608;
$numParts = $files->GetNumBlocks($partSize);
if (($numParts < 1) or ($numParts > 10000)) {
    print 'Use a nonempty source of at most 10,000 fixed 8 MiB parts.' . "\n";
    exit;
}

$remoteEtags = new COM("Chilkat.Hashtable");
$remoteSizes = new COM("Chilkat.Hashtable");
$remoteChecksums = new COM("Chilkat.Hashtable");
$partNumbers = new COM("Chilkat.Hashtable");
$partNumberText = new COM("Chilkat.StringBuilder");
$success = $files->DirEnsureExists($cacheDir);
if ($success != 1) {
    print 'Could not create private checkpoint directory.' . "\n";
    exit;
}

$entries = new COM("Chilkat.DirTree");
$entries->BaseDir = $cacheDir;
$entries->Recurse = 0;
$success = $entries->BeginIterate();
if (($success == 1) or ($entries->DoneIterating != 1)) {
    print 'Start requires an empty checkpoint directory; use resume for an existing upload.' . "\n";
    exit;
}

$random = new COM("Chilkat.Prng");
$uploadToken = $random->genRandom(16,'hex');
if ($random->LastMethodSuccess != 1) {
    print 'Could not create upload identity.' . "\n";
    exit;
}

$query->Clear();
if ($query->Length > 0) {
    $query->Append('&');
}

$query->Append('uploads=');
$query->Append($http->urlEncode(''));
$http->ClearHeaders();
$success = $now->SetFromCurrentSystemTime();
if ($success != 1) {
    print 'Could not read system time.' . "\n";
    exit;
}

$timestamp->SetString($now->getAsTimestamp(0));
$replaceCount = $timestamp->Replace('-','');
$replaceCount = $timestamp->Replace(':','');
$amzDate = $timestamp->getAsString();
$dateStamp = $timestamp->getRange(0,8,0);
$payloadHash = $signer->hashStringENC('');
if ($signer->LastMethodSuccess != 1) {
    print 'Could not hash payload.' . "\n";
    exit;
}

$canonicalHeaders->Clear();
$signedHeaders->Clear();
if ($signedHeaders->Length > 0) {
    $signedHeaders->Append(';');
}

$signedHeaders->Append('host');
$canonicalHeaders->Append('host:');
$canonicalHeaders->Append($host->getAsString());
$canonicalHeaders->Append('\n');
$http->SetRequestHeader('host',$host->getAsString());
if ($signedHeaders->Length > 0) {
    $signedHeaders->Append(';');
}

$signedHeaders->Append('x-amz-checksum-algorithm');
$canonicalHeaders->Append('x-amz-checksum-algorithm:');
$canonicalHeaders->Append('SHA256');
$canonicalHeaders->Append('\n');
$http->SetRequestHeader('x-amz-checksum-algorithm','SHA256');
if ($signedHeaders->Length > 0) {
    $signedHeaders->Append(';');
}

$signedHeaders->Append('x-amz-checksum-type');
$canonicalHeaders->Append('x-amz-checksum-type:');
$canonicalHeaders->Append('COMPOSITE');
$canonicalHeaders->Append('\n');
$http->SetRequestHeader('x-amz-checksum-type','COMPOSITE');
if ($signedHeaders->Length > 0) {
    $signedHeaders->Append(';');
}

$signedHeaders->Append('x-amz-content-sha256');
$canonicalHeaders->Append('x-amz-content-sha256:');
$canonicalHeaders->Append($payloadHash);
$canonicalHeaders->Append('\n');
$http->SetRequestHeader('x-amz-content-sha256',$payloadHash);
if ($signedHeaders->Length > 0) {
    $signedHeaders->Append(';');
}

$signedHeaders->Append('x-amz-date');
$canonicalHeaders->Append('x-amz-date:');
$canonicalHeaders->Append($amzDate);
$canonicalHeaders->Append('\n');
$http->SetRequestHeader('x-amz-date',$amzDate);
if ($signedHeaders->Length > 0) {
    $signedHeaders->Append(';');
}

$signedHeaders->Append('x-amz-meta-source-sha256');
$canonicalHeaders->Append('x-amz-meta-source-sha256:');
$canonicalHeaders->Append($sourceHash);
$canonicalHeaders->Append('\n');
$http->SetRequestHeader('x-amz-meta-source-sha256',$sourceHash);
if ($signedHeaders->Length > 0) {
    $signedHeaders->Append(';');
}

$signedHeaders->Append('x-amz-meta-upload-token');
$canonicalHeaders->Append('x-amz-meta-upload-token:');
$canonicalHeaders->Append($uploadToken);
$canonicalHeaders->Append('\n');
$http->SetRequestHeader('x-amz-meta-upload-token',$uploadToken);
if ($credentials->HasMember('session_token') == 1) {
    if ($signedHeaders->Length > 0) {
        $signedHeaders->Append(';');
    }

    $signedHeaders->Append('x-amz-security-token');
    $canonicalHeaders->Append('x-amz-security-token:');
    $canonicalHeaders->Append($credentials->stringOf('session_token'));
    $canonicalHeaders->Append('\n');
    $http->SetRequestHeader('x-amz-security-token',$credentials->stringOf('session_token'));
}

$canonical->Clear();
$canonical->Append('POST\n');
$canonical->Append($uri->getAsString());
$canonical->Append('\n');
$canonical->Append($query->getAsString());
$canonical->Append('\n');
$canonical->Append($canonicalHeaders->getAsString());
$canonical->Append('\n');
$canonical->Append($signedHeaders->getAsString());
$canonical->Append('\n');
$canonical->Append($payloadHash);
$canonicalHash = $signer->hashStringENC($canonical->getAsString());
if ($signer->LastMethodSuccess != 1) {
    print 'Could not hash canonical request.' . "\n";
    exit;
}

$scope->Clear();
$scope->Append($dateStamp);
$scope->Append('/');
$scope->Append($region);
$scope->Append('/s3/aws4_request');
$stringToSign->Clear();
$stringToSign->Append('AWS4-HMAC-SHA256\n');
$stringToSign->Append($amzDate);
$stringToSign->Append('\n');
$stringToSign->Append($scope->getAsString());
$stringToSign->Append('\n');
$stringToSign->Append($canonicalHash);
$signingKey->SetString('AWS4');
$signingKey->Append($credentials->stringOf('secret_key'));
$success = $signer->SetMacKeyString($signingKey->getAsString());
if ($success != 1) {
    print 'Could not set signing key.' . "\n";
    exit;
}

$derivedKey = $signer->macStringENC($dateStamp);
if ($signer->LastMethodSuccess != 1) {
    print 'Could not derive signing key.' . "\n";
    exit;
}

$success = $signer->SetMacKeyEncoded($derivedKey,'hex');
if ($success != 1) {
    print 'Could not set signing key.' . "\n";
    exit;
}

$derivedKey = $signer->macStringENC($region);
if ($signer->LastMethodSuccess != 1) {
    print 'Could not derive signing key.' . "\n";
    exit;
}

$success = $signer->SetMacKeyEncoded($derivedKey,'hex');
if ($success != 1) {
    print 'Could not set signing key.' . "\n";
    exit;
}

$derivedKey = $signer->macStringENC('s3');
if ($signer->LastMethodSuccess != 1) {
    print 'Could not derive signing key.' . "\n";
    exit;
}

$success = $signer->SetMacKeyEncoded($derivedKey,'hex');
if ($success != 1) {
    print 'Could not set signing key.' . "\n";
    exit;
}

$derivedKey = $signer->macStringENC('aws4_request');
if ($signer->LastMethodSuccess != 1) {
    print 'Could not derive signing key.' . "\n";
    exit;
}

$success = $signer->SetMacKeyEncoded($derivedKey,'hex');
if ($success != 1) {
    print 'Could not set signing key.' . "\n";
    exit;
}

$signature = $signer->macStringENC($stringToSign->getAsString());
if ($signer->LastMethodSuccess != 1) {
    print 'Could not sign request.' . "\n";
    exit;
}

$authorization->Clear();
$authorization->Append('AWS4-HMAC-SHA256 Credential=');
$authorization->Append($credentials->stringOf('access_key'));
$authorization->Append('/');
$authorization->Append($scope->getAsString());
$authorization->Append(', SignedHeaders=');
$authorization->Append($signedHeaders->getAsString());
$authorization->Append(', Signature=');
$authorization->Append($signature);
$http->SetRequestHeader('Authorization',$authorization->getAsString());
$url->SetString('https://');
$url->Append($host->getAsString());
$url->Append($uri->getAsString());
if ($query->Length > 0) {
    $url->Append('?');
    $url->Append($query->getAsString());
}

$success = $http->HttpNoBody('POST',$url->getAsString(),$response);
if (($success != 1) or ($response->StatusCode != 200)) {
    print 'Request failed or returned unexpected HTTP status: ' . $response->StatusCode . "\n";
    //  Preserve progress. Inspect full diagnostics privately; do not log secrets.
    exit;
}

$success = $xml->LoadXml($response->BodyStr);
if ($success != 1) {
    print 'Invalid XML response.' . "\n";
    exit;
}

$stringCompare->SetString($xml->Tag);
$stringMatch4 = $stringCompare->ContentsEqual('InitiateMultipartUploadResult',1);
if ($stringMatch4 != 1) {
    print 'Unexpected XML result, possibly an embedded S3 error. Inspect privately.' . "\n";
    exit;
}

$uploadId = $xml->getChildContent('UploadId');
$stringCompare->SetString($uploadId);
$stringMatch5 = $stringCompare->ContentsEqual('',1);
if (($xml->LastMethodSuccess != 1) or ($stringMatch5 == 1)) {
    print 'Missing required UploadId.' . "\n";
    exit;
}

print 'Created upload ID: ' . $uploadId . "\n";
//  Save the upload ID before sending parts. If saving fails, retain the printed ID.
$success = $state->UpdateString('schema','1');
if ($success != 1) {
    print 'Could not save schema.' . "\n";
    exit;
}

$success = $state->UpdateString('bucket',$bucketName);
if ($success != 1) {
    print 'Could not save bucket.' . "\n";
    exit;
}

$success = $state->UpdateString('key',$objectKey);
if ($success != 1) {
    print 'Could not save key.' . "\n";
    exit;
}

$success = $state->UpdateString('region',$region);
if ($success != 1) {
    print 'Could not save region.' . "\n";
    exit;
}

$success = $state->UpdateString('filePath',$filePath);
if ($success != 1) {
    print 'Could not save filePath.' . "\n";
    exit;
}

$success = $state->UpdateString('fileSize',$fileSize);
if ($success != 1) {
    print 'Could not save fileSize.' . "\n";
    exit;
}

$success = $state->UpdateString('sourceHash',$sourceHash);
if ($success != 1) {
    print 'Could not save sourceHash.' . "\n";
    exit;
}

$success = $state->UpdateString('partSize','8388608');
if ($success != 1) {
    print 'Could not save partSize.' . "\n";
    exit;
}

$success = $state->UpdateString('uploadId',$uploadId);
if ($success != 1) {
    print 'Could not save uploadId.' . "\n";
    exit;
}

$success = $state->UpdateString('uploadToken',$uploadToken);
if ($success != 1) {
    print 'Could not save uploadToken.' . "\n";
    exit;
}

$success = $state->WriteFile('qa_output/s3-multipart/state.json.tmp');
if ($success != 1) {
    print 'Upload was initiated but checkpoint could not be saved; retain its ID.' . "\n";
    exit;
}

$success = $files->FileRename('qa_output/s3-multipart/state.json.tmp',$statePath);
if ($success != 1) {
    print 'Checkpoint rename failed; preserve the temporary checkpoint and upload ID.' . "\n";
    exit;
}

$part = new COM("Chilkat.BinData");
$concatenatedDigests = new COM("Chilkat.BinData");
$completion = new COM("Chilkat.Xml");
$completion->Tag = 'CompleteMultipartUpload';
$completion->AddAttribute('xmlns','http://s3.amazonaws.com/doc/2006-03-01/');
$partIndex = 0;

while (($partIndex < $numParts)) {
    $part->Clear();
    $success = $files->ReadBlockBd($partIndex,$partSize,$part);
    if ($success != 1) {
        print 'Could not read source part; preserve checkpoint.' . "\n";
        exit;
    }

    if (($part->NumBytes == 0) or (($partIndex < $numParts - 1) and ($part->NumBytes != $partSize))) {
        print 'Source changed or part read was incomplete.' . "\n";
        exit;
    }

    $partChecksum = $digest->hashBdENC($part);
    if ($digest->LastMethodSuccess != 1) {
        print 'Could not checksum part.' . "\n";
        exit;
    }

    $partHash = $signer->hashBdENC($part);
    if ($signer->LastMethodSuccess != 1) {
        print 'Could not hash part.' . "\n";
        exit;
    }

    $success = $concatenatedDigests->AppendEncoded($partChecksum,'base64');
    if ($success != 1) {
        print 'Could not accumulate part digests.' . "\n";
        exit;
    }

    $partNumberText->Clear();
    $partNumberText->AppendInt($partIndex + 1);
    $number->Clear();
    $number->AppendInt($part->NumBytes);
    $sizeText = $number->getAsString();
    $partNumberKey = $partNumberText->getAsString();
    $reuse = 0;
    $partEtag = '';
    if ($remoteChecksums->Contains($partNumberKey) == 1) {
        $stringCompare->SetString($remoteChecksums->lookupStr($partNumberKey));
        $stringMatch6 = $stringCompare->ContentsEqual($partChecksum,1);
        $stringCompare->SetString($remoteSizes->lookupStr($partNumberKey));
        $stringMatch7 = $stringCompare->ContentsEqual($sizeText,1);
        if (($stringMatch6 == 1) and ($stringMatch7 == 1)) {
            $partEtag = $remoteEtags->lookupStr($partNumberKey);
            $stringCompare->SetString($partEtag);
            $stringMatch8 = $stringCompare->ContentsEqual('',1);
            if (($remoteEtags->LastMethodSuccess == 1) and ($stringMatch8 != 1)) {
                $reuse = 1;
            }

        }

    }

    if ($reuse != 1) {
        $query->Clear();
        if ($query->Length > 0) {
            $query->Append('&');
        }

        $query->Append('partNumber=');
        $query->Append($http->urlEncode($partNumberText->getAsString()));
        if ($query->Length > 0) {
            $query->Append('&');
        }

        $query->Append('uploadId=');
        $query->Append($http->urlEncode($uploadId));
        $http->ClearHeaders();
        $success = $now->SetFromCurrentSystemTime();
        if ($success != 1) {
            print 'Could not read system time.' . "\n";
            exit;
        }

        $timestamp->SetString($now->getAsTimestamp(0));
        $replaceCount = $timestamp->Replace('-','');
        $replaceCount = $timestamp->Replace(':','');
        $amzDate = $timestamp->getAsString();
        $dateStamp = $timestamp->getRange(0,8,0);
        $payloadHash = $partHash;
        $canonicalHeaders->Clear();
        $signedHeaders->Clear();
        if ($signedHeaders->Length > 0) {
            $signedHeaders->Append(';');
        }

        $signedHeaders->Append('host');
        $canonicalHeaders->Append('host:');
        $canonicalHeaders->Append($host->getAsString());
        $canonicalHeaders->Append('\n');
        $http->SetRequestHeader('host',$host->getAsString());
        if ($signedHeaders->Length > 0) {
            $signedHeaders->Append(';');
        }

        $signedHeaders->Append('x-amz-checksum-sha256');
        $canonicalHeaders->Append('x-amz-checksum-sha256:');
        $canonicalHeaders->Append($partChecksum);
        $canonicalHeaders->Append('\n');
        $http->SetRequestHeader('x-amz-checksum-sha256',$partChecksum);
        if ($signedHeaders->Length > 0) {
            $signedHeaders->Append(';');
        }

        $signedHeaders->Append('x-amz-content-sha256');
        $canonicalHeaders->Append('x-amz-content-sha256:');
        $canonicalHeaders->Append($payloadHash);
        $canonicalHeaders->Append('\n');
        $http->SetRequestHeader('x-amz-content-sha256',$payloadHash);
        if ($signedHeaders->Length > 0) {
            $signedHeaders->Append(';');
        }

        $signedHeaders->Append('x-amz-date');
        $canonicalHeaders->Append('x-amz-date:');
        $canonicalHeaders->Append($amzDate);
        $canonicalHeaders->Append('\n');
        $http->SetRequestHeader('x-amz-date',$amzDate);
        if ($credentials->HasMember('session_token') == 1) {
            if ($signedHeaders->Length > 0) {
                $signedHeaders->Append(';');
            }

            $signedHeaders->Append('x-amz-security-token');
            $canonicalHeaders->Append('x-amz-security-token:');
            $canonicalHeaders->Append($credentials->stringOf('session_token'));
            $canonicalHeaders->Append('\n');
            $http->SetRequestHeader('x-amz-security-token',$credentials->stringOf('session_token'));
        }

        $canonical->Clear();
        $canonical->Append('PUT\n');
        $canonical->Append($uri->getAsString());
        $canonical->Append('\n');
        $canonical->Append($query->getAsString());
        $canonical->Append('\n');
        $canonical->Append($canonicalHeaders->getAsString());
        $canonical->Append('\n');
        $canonical->Append($signedHeaders->getAsString());
        $canonical->Append('\n');
        $canonical->Append($payloadHash);
        $canonicalHash = $signer->hashStringENC($canonical->getAsString());
        if ($signer->LastMethodSuccess != 1) {
            print 'Could not hash canonical request.' . "\n";
            exit;
        }

        $scope->Clear();
        $scope->Append($dateStamp);
        $scope->Append('/');
        $scope->Append($region);
        $scope->Append('/s3/aws4_request');
        $stringToSign->Clear();
        $stringToSign->Append('AWS4-HMAC-SHA256\n');
        $stringToSign->Append($amzDate);
        $stringToSign->Append('\n');
        $stringToSign->Append($scope->getAsString());
        $stringToSign->Append('\n');
        $stringToSign->Append($canonicalHash);
        $signingKey->SetString('AWS4');
        $signingKey->Append($credentials->stringOf('secret_key'));
        $success = $signer->SetMacKeyString($signingKey->getAsString());
        if ($success != 1) {
            print 'Could not set signing key.' . "\n";
            exit;
        }

        $derivedKey = $signer->macStringENC($dateStamp);
        if ($signer->LastMethodSuccess != 1) {
            print 'Could not derive signing key.' . "\n";
            exit;
        }

        $success = $signer->SetMacKeyEncoded($derivedKey,'hex');
        if ($success != 1) {
            print 'Could not set signing key.' . "\n";
            exit;
        }

        $derivedKey = $signer->macStringENC($region);
        if ($signer->LastMethodSuccess != 1) {
            print 'Could not derive signing key.' . "\n";
            exit;
        }

        $success = $signer->SetMacKeyEncoded($derivedKey,'hex');
        if ($success != 1) {
            print 'Could not set signing key.' . "\n";
            exit;
        }

        $derivedKey = $signer->macStringENC('s3');
        if ($signer->LastMethodSuccess != 1) {
            print 'Could not derive signing key.' . "\n";
            exit;
        }

        $success = $signer->SetMacKeyEncoded($derivedKey,'hex');
        if ($success != 1) {
            print 'Could not set signing key.' . "\n";
            exit;
        }

        $derivedKey = $signer->macStringENC('aws4_request');
        if ($signer->LastMethodSuccess != 1) {
            print 'Could not derive signing key.' . "\n";
            exit;
        }

        $success = $signer->SetMacKeyEncoded($derivedKey,'hex');
        if ($success != 1) {
            print 'Could not set signing key.' . "\n";
            exit;
        }

        $signature = $signer->macStringENC($stringToSign->getAsString());
        if ($signer->LastMethodSuccess != 1) {
            print 'Could not sign request.' . "\n";
            exit;
        }

        $authorization->Clear();
        $authorization->Append('AWS4-HMAC-SHA256 Credential=');
        $authorization->Append($credentials->stringOf('access_key'));
        $authorization->Append('/');
        $authorization->Append($scope->getAsString());
        $authorization->Append(', SignedHeaders=');
        $authorization->Append($signedHeaders->getAsString());
        $authorization->Append(', Signature=');
        $authorization->Append($signature);
        $http->SetRequestHeader('Authorization',$authorization->getAsString());
        $url->SetString('https://');
        $url->Append($host->getAsString());
        $url->Append($uri->getAsString());
        if ($query->Length > 0) {
            $url->Append('?');
            $url->Append($query->getAsString());
        }

        $success = $http->HttpBd('PUT',$url->getAsString(),$part,'application/octet-stream',$response);
        if (($success != 1) or ($response->StatusCode != 200)) {
            print 'Request failed or returned unexpected HTTP status: ' . $response->StatusCode . "\n";
            //  Preserve progress. Inspect full diagnostics privately; do not log secrets.
            exit;
        }

        $confirmed = $response->getHeaderField('x-amz-checksum-sha256');
        $stringCompare->SetString($confirmed);
        $stringMatch9 = $stringCompare->ContentsEqual('',1);
        if (($response->LastMethodSuccess != 1) or ($stringMatch9 == 1)) {
            print 'Missing required response header x-amz-checksum-sha256.' . "\n";
            exit;
        }

        $stringCompare->SetString($confirmed);
        $stringMatch10 = $stringCompare->ContentsEqual($partChecksum,1);
        if ($stringMatch10 != 1) {
            print 'Part checksum mismatch; preserve checkpoint.' . "\n";
            exit;
        }

        $partEtag = $response->getHeaderField('ETag');
        $stringCompare->SetString($partEtag);
        $stringMatch11 = $stringCompare->ContentsEqual('',1);
        if (($response->LastMethodSuccess != 1) or ($stringMatch11 == 1)) {
            print 'Missing required response header ETag.' . "\n";
            exit;
        }

    }
    else {
        print 'Reusing verified remote part: ' . $partNumberText->getAsString() . "\n";
    }

    $completion->I = $partIndex;
    $completion->UpdateChildContent('Part[i]|PartNumber',$partNumberText->getAsString());
    $completion->UpdateChildContent('Part[i]|ETag',$partEtag);
    $completion->UpdateChildContent('Part[i]|ChecksumSHA256',$partChecksum);
    $partIndex = $partIndex + 1;
}

$files->FileClose();
//  Recheck the entire immutable source before committing its parts.
$finalSourceHash = $signer->hashFileENC($filePath);
$stringCompare->SetString($finalSourceHash);
$stringMatch12 = $stringCompare->ContentsEqual($sourceHash,1);
if (($signer->LastMethodSuccess != 1) or ($stringMatch12 != 1)) {
    print 'Source changed; completion was not sent.' . "\n";
    exit;
}

$compositeChecksum = $digest->hashBdENC($concatenatedDigests);
if ($digest->LastMethodSuccess != 1) {
    print 'Could not compute composite checksum.' . "\n";
    exit;
}

$number->SetString($compositeChecksum);
$number->Append('-');
$number->AppendInt($numParts);
$compositeChecksum = $number->getAsString();
$success = $pending->UpdateString('uploadId',$uploadId);
if ($success != 1) {
    print 'Could not save uploadId.' . "\n";
    exit;
}

$success = $pending->UpdateString('sourceHash',$sourceHash);
if ($success != 1) {
    print 'Could not save sourceHash.' . "\n";
    exit;
}

$success = $pending->UpdateString('uploadToken',$uploadToken);
if ($success != 1) {
    print 'Could not save uploadToken.' . "\n";
    exit;
}

$success = $pending->UpdateString('checksum',$compositeChecksum);
if ($success != 1) {
    print 'Could not save checksum.' . "\n";
    exit;
}

$success = $pending->WriteFile($pendingPath);
if ($success != 1) {
    print 'Could not save completion recovery record.' . "\n";
    exit;
}

$requestBody = $completion->getXml();
$query->Clear();
if ($query->Length > 0) {
    $query->Append('&');
}

$query->Append('uploadId=');
$query->Append($http->urlEncode($uploadId));
$http->ClearHeaders();
$success = $now->SetFromCurrentSystemTime();
if ($success != 1) {
    print 'Could not read system time.' . "\n";
    exit;
}

$timestamp->SetString($now->getAsTimestamp(0));
$replaceCount = $timestamp->Replace('-','');
$replaceCount = $timestamp->Replace(':','');
$amzDate = $timestamp->getAsString();
$dateStamp = $timestamp->getRange(0,8,0);
$payloadHash = $signer->hashStringENC($requestBody);
if ($signer->LastMethodSuccess != 1) {
    print 'Could not hash payload.' . "\n";
    exit;
}

$canonicalHeaders->Clear();
$signedHeaders->Clear();
if ($signedHeaders->Length > 0) {
    $signedHeaders->Append(';');
}

$signedHeaders->Append('host');
$canonicalHeaders->Append('host:');
$canonicalHeaders->Append($host->getAsString());
$canonicalHeaders->Append('\n');
$http->SetRequestHeader('host',$host->getAsString());
if ($signedHeaders->Length > 0) {
    $signedHeaders->Append(';');
}

$signedHeaders->Append('x-amz-checksum-type');
$canonicalHeaders->Append('x-amz-checksum-type:');
$canonicalHeaders->Append('COMPOSITE');
$canonicalHeaders->Append('\n');
$http->SetRequestHeader('x-amz-checksum-type','COMPOSITE');
if ($signedHeaders->Length > 0) {
    $signedHeaders->Append(';');
}

$signedHeaders->Append('x-amz-content-sha256');
$canonicalHeaders->Append('x-amz-content-sha256:');
$canonicalHeaders->Append($payloadHash);
$canonicalHeaders->Append('\n');
$http->SetRequestHeader('x-amz-content-sha256',$payloadHash);
if ($signedHeaders->Length > 0) {
    $signedHeaders->Append(';');
}

$signedHeaders->Append('x-amz-date');
$canonicalHeaders->Append('x-amz-date:');
$canonicalHeaders->Append($amzDate);
$canonicalHeaders->Append('\n');
$http->SetRequestHeader('x-amz-date',$amzDate);
if ($credentials->HasMember('session_token') == 1) {
    if ($signedHeaders->Length > 0) {
        $signedHeaders->Append(';');
    }

    $signedHeaders->Append('x-amz-security-token');
    $canonicalHeaders->Append('x-amz-security-token:');
    $canonicalHeaders->Append($credentials->stringOf('session_token'));
    $canonicalHeaders->Append('\n');
    $http->SetRequestHeader('x-amz-security-token',$credentials->stringOf('session_token'));
}

$canonical->Clear();
$canonical->Append('POST\n');
$canonical->Append($uri->getAsString());
$canonical->Append('\n');
$canonical->Append($query->getAsString());
$canonical->Append('\n');
$canonical->Append($canonicalHeaders->getAsString());
$canonical->Append('\n');
$canonical->Append($signedHeaders->getAsString());
$canonical->Append('\n');
$canonical->Append($payloadHash);
$canonicalHash = $signer->hashStringENC($canonical->getAsString());
if ($signer->LastMethodSuccess != 1) {
    print 'Could not hash canonical request.' . "\n";
    exit;
}

$scope->Clear();
$scope->Append($dateStamp);
$scope->Append('/');
$scope->Append($region);
$scope->Append('/s3/aws4_request');
$stringToSign->Clear();
$stringToSign->Append('AWS4-HMAC-SHA256\n');
$stringToSign->Append($amzDate);
$stringToSign->Append('\n');
$stringToSign->Append($scope->getAsString());
$stringToSign->Append('\n');
$stringToSign->Append($canonicalHash);
$signingKey->SetString('AWS4');
$signingKey->Append($credentials->stringOf('secret_key'));
$success = $signer->SetMacKeyString($signingKey->getAsString());
if ($success != 1) {
    print 'Could not set signing key.' . "\n";
    exit;
}

$derivedKey = $signer->macStringENC($dateStamp);
if ($signer->LastMethodSuccess != 1) {
    print 'Could not derive signing key.' . "\n";
    exit;
}

$success = $signer->SetMacKeyEncoded($derivedKey,'hex');
if ($success != 1) {
    print 'Could not set signing key.' . "\n";
    exit;
}

$derivedKey = $signer->macStringENC($region);
if ($signer->LastMethodSuccess != 1) {
    print 'Could not derive signing key.' . "\n";
    exit;
}

$success = $signer->SetMacKeyEncoded($derivedKey,'hex');
if ($success != 1) {
    print 'Could not set signing key.' . "\n";
    exit;
}

$derivedKey = $signer->macStringENC('s3');
if ($signer->LastMethodSuccess != 1) {
    print 'Could not derive signing key.' . "\n";
    exit;
}

$success = $signer->SetMacKeyEncoded($derivedKey,'hex');
if ($success != 1) {
    print 'Could not set signing key.' . "\n";
    exit;
}

$derivedKey = $signer->macStringENC('aws4_request');
if ($signer->LastMethodSuccess != 1) {
    print 'Could not derive signing key.' . "\n";
    exit;
}

$success = $signer->SetMacKeyEncoded($derivedKey,'hex');
if ($success != 1) {
    print 'Could not set signing key.' . "\n";
    exit;
}

$signature = $signer->macStringENC($stringToSign->getAsString());
if ($signer->LastMethodSuccess != 1) {
    print 'Could not sign request.' . "\n";
    exit;
}

$authorization->Clear();
$authorization->Append('AWS4-HMAC-SHA256 Credential=');
$authorization->Append($credentials->stringOf('access_key'));
$authorization->Append('/');
$authorization->Append($scope->getAsString());
$authorization->Append(', SignedHeaders=');
$authorization->Append($signedHeaders->getAsString());
$authorization->Append(', Signature=');
$authorization->Append($signature);
$http->SetRequestHeader('Authorization',$authorization->getAsString());
$url->SetString('https://');
$url->Append($host->getAsString());
$url->Append($uri->getAsString());
if ($query->Length > 0) {
    $url->Append('?');
    $url->Append($query->getAsString());
}

$success = $http->HttpStr('POST',$url->getAsString(),$requestBody,'utf-8','application/xml',$response);
if (($success != 1) or ($response->StatusCode != 200)) {
    print 'Request failed or returned unexpected HTTP status: ' . $response->StatusCode . "\n";
    //  Preserve progress. Inspect full diagnostics privately; do not log secrets.
    exit;
}

$success = $xml->LoadXml($response->BodyStr);
if ($success != 1) {
    print 'Invalid XML response.' . "\n";
    exit;
}

$stringCompare->SetString($xml->Tag);
$stringMatch13 = $stringCompare->ContentsEqual('CompleteMultipartUploadResult',1);
if ($stringMatch13 != 1) {
    print 'Unexpected XML result, possibly an embedded S3 error. Inspect privately.' . "\n";
    exit;
}

$confirmed = $xml->getChildContent('ChecksumSHA256');
$stringCompare->SetString($confirmed);
$stringMatch14 = $stringCompare->ContentsEqual('',1);
if (($xml->LastMethodSuccess != 1) or ($stringMatch14 == 1)) {
    print 'Missing required ChecksumSHA256.' . "\n";
    exit;
}

$stringCompare->SetString($confirmed);
$stringMatch15 = $stringCompare->ContentsEqual($compositeChecksum,1);
if ($stringMatch15 != 1) {
    print 'Completion checksum differs; preserve checkpoint and inspect object.' . "\n";
    exit;
}

$success = $state->UpdateString('compositeChecksum',$compositeChecksum);
if ($success != 1) {
    print 'Could not save compositeChecksum.' . "\n";
    exit;
}

$success = $state->WriteFile('qa_output/s3-multipart/completed.json.tmp');
if ($success != 1) {
    print 'Completion succeeded but receipt could not be saved; preserve the checkpoint.' . "\n";
    exit;
}

$success = $files->FileRename('qa_output/s3-multipart/completed.json.tmp',$receiptPath);
if ($success != 1) {
    print 'Completion receipt remains at its temporary path.' . "\n";
    exit;
}

print 'Multipart upload completed and verified.' . "\n";

?>