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

Azure Blob: Resume a Download with ETag Protection

See more Azure Cloud Storage Examples

Save the account, path, ETag and size in an immutable checkpoint, then append complete byte ranges to a private .part file. A later run uses the existing partial-file length as its offset and checks that HEAD still describes the same blob. Every range carries If-Match and must return the expected ETag, exact Content-Range, Content-Length and body size before any bytes are appended.

The demonstration bounds offsets to 2,000,000,000 bytes so it can use int arithmetic without overflow; this is not an Azure service limit. Sizes in checkpoints remain strings. Only the final successful transfer renames the partial output to the final filename. Empty blobs are handled without issuing an invalid range.

Use one process, an exclusive local destination and an unchanged partial file. The checkpoint does not independently hash or authenticate local content; do not point it at an unrelated file or reuse a partial file that was edited or suffered disk corruption. After a local write failure inspect or restart the partial file. On 412 or changed HEAD properties, preserve the previous partial output and start a new download separately instead of combining versions. A crash while initially publishing the checkpoint fails closed if state is incomplete.

Uses direct Chilkat.Rest requests and Azure public-cloud endpoints with verified HTTPS. REST requests select service version 2026-04-06. Create local input/output directories before running. Account-key examples read account and access_key string fields from private qa_data/azure/storage.json; do not embed secrets in distributed applications. Entra examples explain their own configuration. Keep credentials, bearer tokens, SAS URLs and diagnostic dumps private. Shared Key is supported only where allowed by account policy; Entra authentication is preferred where available.

Transport success and HTTP status are checked separately. Writes are not automatically replayed after an uncertain response. IDs, ETags, continuation markers and file sizes are strings; counters and explicitly bounded offsets use int. No webhook or web server is required.

Microsoft reference.

Chilkat PHP ActiveX Downloads

PHP ActiveX
<?php

$success = 0;

//  StringBuilder compares text by value in every generated language.
$textCompare = new COM("Chilkat.StringBuilder");
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
$success = 0;
$config = new COM("Chilkat.JsonObject");
$config->Strict = 1;
$success = $config->LoadFile('qa_data/azure/storage.json');
if ($success != 1) {
    print 'Could not load private Azure configuration.' . "\n";
    exit;
}

$textCompare->Clear();
$textCompare->SetString($config->stringOf('account'));
$sameText1 = $textCompare->ContentsEqual('',1);
if (($config->JsonTypeOf('account') != 1) or ($sameText1 == 1)) {
    print 'Supply the storage account name.' . "\n";
    exit;
}

//  access_key is the base64 account key, not a connection string or SAS.
$textCompare->Clear();
$textCompare->SetString($config->stringOf('access_key'));
$sameText2 = $textCompare->ContentsEqual('',1);
if (($config->JsonTypeOf('access_key') != 1) or ($sameText2 == 1)) {
    print 'Supply the base64 account access key.' . "\n";
    exit;
}

$endpoint = new COM("Chilkat.StringBuilder");
$success = $endpoint->Append($config->stringOf('account'));
if ($success != 1) {
    print 'Could not prepare the request.' . "\n";
    exit;
}

$success = $endpoint->Append('.blob.core.windows.net');
if ($success != 1) {
    print 'Could not prepare the request.' . "\n";
    exit;
}

//  resourcePath is already URL-encoded. Encode each path segment once when adapting it.
//  Keep slash separators; names and paths are case-sensitive.
$resourcePath = '/examplecontainer/example.bin';
$rest = new COM("Chilkat.Rest");
$rest->ConnectTimeoutMs = 20000;
$rest->IdleTimeoutMs = 60000;
$azAuth = new COM("Chilkat.AuthAzureStorage");
$azAuth->Account = $config->stringOf('account');
$azAuth->AccessKey = $config->stringOf('access_key');
$azAuth->Service = 'Blob';
$azAuth->Scheme = 'SharedKey';
$azAuth->XMsVersion = '2026-04-06';
$success = $rest->SetAuthAzureStorage($azAuth);
if ($success != 1) {
    print 'Could not configure Shared Key signing.' . "\n";
    exit;
}

$connection = new COM("Chilkat.Socket");
$connection->RequireSslCertVerify = 1;
$connection->MaxReadIdleMs = 60000;
$connection->MaxSendIdleMs = 60000;
$success = $connection->Connect($endpoint->getAsString(),443,1,20000);
if ($success != 1) {
    print 'TLS connection failed; inspect diagnostics privately.' . "\n";
    exit;
}

//  Do not replay a write automatically after losing its response.
$success = $rest->UseConnection($connection,0);
if ($success != 1) {
    print 'Could not prepare the request.' . "\n";
    exit;
}

$result = new COM("Chilkat.Xml");
$result->Strict = 1;
$partFile = 'qa_output/resume.bin.part';
$finalFile = 'qa_output/resume.bin';
$checkpointFile = 'qa_data/azure/download-checkpoint.json';
$files = new COM("Chilkat.FileAccess");
if ($files->FileExists($finalFile) == 1) {
    print 'Choose a new final filename; existing output is preserved.' . "\n";
    exit;
}

$responseText = $rest->fullRequestNoBody('HEAD',$resourcePath);
if ($rest->LastMethodSuccess != 1) {
    print 'Request did not complete; outcome may be uncertain.' . "\n";
    exit;
}

if ($rest->ResponseStatusCode != 200) {
    print 'HTTP status: ' . $rest->ResponseStatusCode . "\n";
    print 'Azure error code: ' . $rest->responseHdrByName('x-ms-error-code') . "\n";
    print 'Request ID: ' . $rest->responseHdrByName('x-ms-request-id') . "\n";
    //  Inspect any error body privately; do not log credentials, SAS URLs or payloads.
    exit;
}

$etag = $rest->responseHdrByName('ETag');
$textCompare->Clear();
$textCompare->SetString($etag);
$sameText3 = $textCompare->ContentsEqual('',1);
if ($sameText3 == 1) {
    print 'Missing blob ETag.' . "\n";
    exit;
}

$totalText = $rest->responseHdrByName('Content-Length');
$totalValue = new COM("Chilkat.StringBuilder");
$success = $totalValue->Append($totalText);
if ($success != 1) {
    print 'Could not prepare the request.' . "\n";
    exit;
}

if (($totalValue->Length < 1) or ($totalValue->Length > 10)) {
    print 'Invalid or oversized length for this bounded example.' . "\n";
    exit;
}

$totalDigits = new COM("Chilkat.StringBuilder");
$success = $totalDigits->Append($totalText);
if ($success != 1) {
    print 'Could not prepare the request.' . "\n";
    exit;
}

$totalRemoved = 0;
$totalRemoved = $totalDigits->Replace('0','');
$totalRemoved = $totalDigits->Replace('1','');
$totalRemoved = $totalDigits->Replace('2','');
$totalRemoved = $totalDigits->Replace('3','');
$totalRemoved = $totalDigits->Replace('4','');
$totalRemoved = $totalDigits->Replace('5','');
$totalRemoved = $totalDigits->Replace('6','');
$totalRemoved = $totalDigits->Replace('7','');
$totalRemoved = $totalDigits->Replace('8','');
$totalRemoved = $totalDigits->Replace('9','');
if ($totalDigits->Length != 0) {
    print 'Length must be a decimal string.' . "\n";
    exit;
}

if (($totalValue->Length == 10) and ($totalValue->StartsWith('1',1) != 1) and ($totalValue->ContentsEqual('2000000000',1) != 1)) {
    print 'Length exceeds the 2,000,000,000-byte demonstration bound.' . "\n";
    exit;
}

$totalNumber = new COM("Chilkat.JsonObject");
$success = $totalNumber->UpdateNumber('value',$totalText);
if ($success != 1) {
    print 'Could not prepare the request.' . "\n";
    exit;
}

$total = $totalNumber->IntOf('value');
$checkpoint = new COM("Chilkat.JsonObject");
$checkpoint->Strict = 1;
if ($files->FileExists($checkpointFile) == 1) {
    $success = $checkpoint->LoadFile($checkpointFile);
    if ($success != 1) {
        print 'Invalid checkpoint.' . "\n";
        exit;
    }

    $textCompare->Clear();
    $textCompare->SetString($checkpoint->stringOf('path'));
    $sameText4 = $textCompare->ContentsEqual($resourcePath,1);
    $textCompare->Clear();
    $textCompare->SetString($checkpoint->stringOf('etag'));
    $sameText5 = $textCompare->ContentsEqual($etag,1);
    $textCompare->Clear();
    $textCompare->SetString($checkpoint->stringOf('size'));
    $sameText6 = $textCompare->ContentsEqual($totalText,1);
    if (($checkpoint->stringOf('account') != $config->stringOf('account')) or ($sameText4 != 1) or ($sameText5 != 1) or ($sameText6 != 1)) {
        print 'The remote blob or checkpoint target changed. Preserve the old partial output and restart separately.' . "\n";
        exit;
    }

}
else {
    if ($files->FileExists($partFile) == 1) {
        print 'Partial file exists without its checkpoint; refusing to append.' . "\n";
        exit;
    }

    $success = $checkpoint->UpdateString('account',$config->stringOf('account'));
    if ($success != 1) {
        print 'Could not prepare the request.' . "\n";
        exit;
    }

    $success = $checkpoint->UpdateString('path',$resourcePath);
    if ($success != 1) {
        print 'Could not prepare the request.' . "\n";
        exit;
    }

    $success = $checkpoint->UpdateString('etag',$etag);
    if ($success != 1) {
        print 'Could not prepare the request.' . "\n";
        exit;
    }

    $success = $checkpoint->UpdateString('size',$totalText);
    if ($success != 1) {
        print 'Could not prepare the request.' . "\n";
        exit;
    }

    $success = $checkpoint->WriteFile('qa_data/azure/download-checkpoint.tmp');
    if ($success != 1) {
        print 'Could not write checkpoint.' . "\n";
        exit;
    }

    $success = $files->FileRename('qa_data/azure/download-checkpoint.tmp',$checkpointFile);
    if ($success != 1) {
        print 'Could not publish checkpoint.' . "\n";
        exit;
    }

}

//  The immutable checkpoint identifies the version. Actual local length is the resume offset.
//  Keep this partial file private, unchanged and exclusive to this one download.
$localSize = '0';
if ($files->FileExists($partFile) == 1) {
    $localSize = $files->fileSizeStr($partFile);
    if ($files->LastMethodSuccess != 1) {
        print 'Could not get partial-file size.' . "\n";
        exit;
    }

}

$offsetText = $localSize;
$offsetValue = new COM("Chilkat.StringBuilder");
$success = $offsetValue->Append($offsetText);
if ($success != 1) {
    print 'Could not prepare the request.' . "\n";
    exit;
}

if (($offsetValue->Length < 1) or ($offsetValue->Length > 10)) {
    print 'Invalid or oversized length for this bounded example.' . "\n";
    exit;
}

$offsetDigits = new COM("Chilkat.StringBuilder");
$success = $offsetDigits->Append($offsetText);
if ($success != 1) {
    print 'Could not prepare the request.' . "\n";
    exit;
}

$offsetRemoved = 0;
$offsetRemoved = $offsetDigits->Replace('0','');
$offsetRemoved = $offsetDigits->Replace('1','');
$offsetRemoved = $offsetDigits->Replace('2','');
$offsetRemoved = $offsetDigits->Replace('3','');
$offsetRemoved = $offsetDigits->Replace('4','');
$offsetRemoved = $offsetDigits->Replace('5','');
$offsetRemoved = $offsetDigits->Replace('6','');
$offsetRemoved = $offsetDigits->Replace('7','');
$offsetRemoved = $offsetDigits->Replace('8','');
$offsetRemoved = $offsetDigits->Replace('9','');
if ($offsetDigits->Length != 0) {
    print 'Length must be a decimal string.' . "\n";
    exit;
}

if (($offsetValue->Length == 10) and ($offsetValue->StartsWith('1',1) != 1) and ($offsetValue->ContentsEqual('2000000000',1) != 1)) {
    print 'Length exceeds the 2,000,000,000-byte demonstration bound.' . "\n";
    exit;
}

$offsetNumber = new COM("Chilkat.JsonObject");
$success = $offsetNumber->UpdateNumber('value',$offsetText);
if ($success != 1) {
    print 'Could not prepare the request.' . "\n";
    exit;
}

$offset = $offsetNumber->IntOf('value');
if ($offset > $total) {
    print 'Partial file is longer than the selected blob.' . "\n";
    exit;
}

//  Ensure an empty blob also creates a local file.
$success = $files->OpenForAppend($partFile);
if ($success != 1) {
    print 'Could not open partial file.' . "\n";
    exit;
}

$files->FileClose();
$success = $rest->AddHeader('If-Match',$etag);
if ($success != 1) {
    print 'Could not prepare the request.' . "\n";
    exit;
}

$chunk = new COM("Chilkat.BinData");
$range = new COM("Chilkat.StringBuilder");
$expectedRange = new COM("Chilkat.StringBuilder");
$expectedLength = new COM("Chilkat.StringBuilder");
while (($offset < $total)) {
    $count = $total - $offset;
    if ($count > 4194304) {
        $count = 4194304;
    }

    $endByte = $offset + $count - 1;
    $range->Clear();
    $success = $range->Append('bytes=');
    if ($success != 1) {
        print 'Could not prepare the request.' . "\n";
        exit;
    }

    $success = $range->AppendInt($offset);
    if ($success != 1) {
        print 'Could not prepare the request.' . "\n";
        exit;
    }

    $success = $range->Append('-');
    if ($success != 1) {
        print 'Could not prepare the request.' . "\n";
        exit;
    }

    $success = $range->AppendInt($endByte);
    if ($success != 1) {
        print 'Could not prepare the request.' . "\n";
        exit;
    }

    $success = $rest->AddHeader('x-ms-range',$range->getAsString());
    if ($success != 1) {
        print 'Could not prepare the request.' . "\n";
        exit;
    }

    $expectedRange->Clear();
    $success = $expectedRange->Append('bytes ');
    if ($success != 1) {
        print 'Could not prepare the request.' . "\n";
        exit;
    }

    $success = $expectedRange->AppendInt($offset);
    if ($success != 1) {
        print 'Could not prepare the request.' . "\n";
        exit;
    }

    $success = $expectedRange->Append('-');
    if ($success != 1) {
        print 'Could not prepare the request.' . "\n";
        exit;
    }

    $success = $expectedRange->AppendInt($endByte);
    if ($success != 1) {
        print 'Could not prepare the request.' . "\n";
        exit;
    }

    $success = $expectedRange->Append('/');
    if ($success != 1) {
        print 'Could not prepare the request.' . "\n";
        exit;
    }

    $success = $expectedRange->Append($totalText);
    if ($success != 1) {
        print 'Could not prepare the request.' . "\n";
        exit;
    }

    $expectedLength->Clear();
    $success = $expectedLength->AppendInt($count);
    if ($success != 1) {
        print 'Could not prepare the request.' . "\n";
        exit;
    }

    $rest->Disconnect(10);
    $success = $connection->Connect($endpoint->getAsString(),443,1,20000);
    if ($success != 1) {
        print 'TLS reconnection failed.' . "\n";
        exit;
    }

    $success = $rest->UseConnection($connection,0);
    if ($success != 1) {
        print 'Could not prepare the request.' . "\n";
        exit;
    }

    $success = $rest->SendReqNoBody('GET',$resourcePath);
    if ($success != 1) {
        print 'Could not prepare the request.' . "\n";
        exit;
    }

    $httpStatus = $rest->ReadResponseHeader();
    if ($httpStatus < 0) {
        print 'Could not read range response headers.' . "\n";
        exit;
    }

    if ($rest->ResponseStatusCode != 206) {
        print 'HTTP status: ' . $rest->ResponseStatusCode . "\n";
        print 'Azure error code: ' . $rest->responseHdrByName('x-ms-error-code') . "\n";
        print 'Request ID: ' . $rest->responseHdrByName('x-ms-request-id') . "\n";
        //  Inspect any error body privately; do not log credentials, SAS URLs or payloads.
        exit;
    }

    $textCompare->Clear();
    $textCompare->SetString($rest->responseHdrByName('ETag'));
    $sameText7 = $textCompare->ContentsEqual($etag,1);
    if (($sameText7 != 1) or ($rest->responseHdrByName('Content-Range') != $expectedRange->getAsString()) or ($rest->responseHdrByName('Content-Length') != $expectedLength->getAsString())) {
        print 'Unexpected range response; no bytes appended.' . "\n";
        exit;
    }

    $success = $chunk->Clear();
    if ($success != 1) {
        print 'Could not prepare the request.' . "\n";
        exit;
    }

    $success = $rest->ReadRespBd($chunk);
    if ($success != 1) {
        print 'Incomplete range body; no bytes appended.' . "\n";
        exit;
    }

    if ($chunk->NumBytes != $count) {
        print 'Wrong byte count; no bytes appended.' . "\n";
        exit;
    }

    $success = $files->OpenForAppend($partFile);
    if ($success != 1) {
        print 'Could not reopen partial file.' . "\n";
        exit;
    }

    $success = $files->FileWriteBd($chunk,0,0);
    $files->FileClose();
    if ($success != 1) {
        print 'Local write failed. Inspect the partial file before retrying.' . "\n";
        exit;
    }

    $offset = $offset + $count;
}

$success = $files->FileRename($partFile,$finalFile);
if ($success != 1) {
    print 'Could not publish completed download.' . "\n";
    exit;
}

print 'Download complete. Retain or archive the checkpoint with the completed file.' . "\n";

?>