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

S3: List All Buckets with STS Credentials

See more AWS Security Token Service Examples

Uses all three temporary credential fields from the private XML file produced by either GetSessionToken or AssumeRole. Validates the response root, nonempty credential fields and ISO 8601 expiration before connecting, then checks expiry with a 60-second margin before each page. Does not print credential data, renew it automatically, or infer freshness merely from the presence of a file.

Uses Chilkat.Rest/AuthAws with Signature Version 4, service s3, explicit us-west-2 signing region, a matching regional endpoint, and TLS certificate verification. STS issuance region does not fix the service-request signing region. The session token is sent in the signed query on every request; do not log the request URL. Configure the appropriate endpoint for other partitions.

Requests max-buckets=100 and follows S3's ContinuationToken, including after an empty page. Tokens are opaque, repeated tokens stop enumeration, and a 10,000-page bound reports incomplete results. Requires s3:ListAllMyBuckets. Lists general purpose buckets owned by the authenticated account, not every bucket the caller can access. Directory buckets are excluded. Does not depend on Owner.DisplayName. Pagination is important for accounts with elevated bucket quotas, where unpaginated listing is rejected.

Pre-protect the credential file and output environment. This read-only consumer does not change the XML file. A production credential provider should coordinate refresh and publication of a complete credential set rather than partially updating it while requests are running.

AWS API reference

Chilkat PHP ActiveX Downloads

PHP ActiveX
<?php

$success = 0;

$stringCompare = new COM("Chilkat.StringBuilder");
//  Assumes Chilkat is unlocked. See Global Unlock Sample.
//  Accept the private XML handoff from either GetSessionToken or AssumeRole.
$xmlToken = new COM("Chilkat.Xml");
$xmlToken->Strict = 1;
$success = $xmlToken->LoadXmlFile('qa_data/tokens/aws_session_token.xml');
if ($success != 1) {
    print 'Could not load the private STS credential file.' . "\n";
    exit;
}

$credentialPath = '';
$stringCompare->SetString($xmlToken->Tag);
$stringMatch1 = $stringCompare->ContentsEqual('GetSessionTokenResponse',1);
if ($stringMatch1 == 1) {
    $credentialPath = 'GetSessionTokenResult|Credentials';
}

$stringCompare->SetString($xmlToken->Tag);
$stringMatch2 = $stringCompare->ContentsEqual('AssumeRoleResponse',1);
if ($stringMatch2 == 1) {
    $credentialPath = 'AssumeRoleResult|Credentials';
}

$stringCompare->SetString($credentialPath);
$stringMatch3 = $stringCompare->ContentsEqual('',1);
if ($stringMatch3 == 1) {
    print 'Expected a GetSessionToken or AssumeRole credential response.' . "\n";
    exit;
}

$path = new COM("Chilkat.StringBuilder");
$success = $path->SetString($credentialPath);
if ($success != 1) {
    print 'Could not build credential path.' . "\n";
    exit;
}

$success = $path->Append('|AccessKeyId');
if ($success != 1) {
    print 'Could not build credential path.' . "\n";
    exit;
}

$accessKey = $xmlToken->getChildContent($path->getAsString());
$stringCompare->SetString($accessKey);
$stringMatch4 = $stringCompare->ContentsEqual('',1);
if (($xmlToken->LastMethodSuccess != 1) or ($stringMatch4 == 1)) {
    print 'Missing or empty AccessKeyId.' . "\n";
    exit;
}

$success = $path->SetString($credentialPath);
if ($success != 1) {
    print 'Could not build credential path.' . "\n";
    exit;
}

$success = $path->Append('|SecretAccessKey');
if ($success != 1) {
    print 'Could not build credential path.' . "\n";
    exit;
}

$secretKey = $xmlToken->getChildContent($path->getAsString());
$stringCompare->SetString($secretKey);
$stringMatch5 = $stringCompare->ContentsEqual('',1);
if (($xmlToken->LastMethodSuccess != 1) or ($stringMatch5 == 1)) {
    print 'Missing or empty SecretAccessKey.' . "\n";
    exit;
}

$success = $path->SetString($credentialPath);
if ($success != 1) {
    print 'Could not build credential path.' . "\n";
    exit;
}

$success = $path->Append('|SessionToken');
if ($success != 1) {
    print 'Could not build credential path.' . "\n";
    exit;
}

$sessionToken = $xmlToken->getChildContent($path->getAsString());
$stringCompare->SetString($sessionToken);
$stringMatch6 = $stringCompare->ContentsEqual('',1);
if (($xmlToken->LastMethodSuccess != 1) or ($stringMatch6 == 1)) {
    print 'Missing or empty SessionToken.' . "\n";
    exit;
}

$success = $path->SetString($credentialPath);
if ($success != 1) {
    print 'Could not build credential path.' . "\n";
    exit;
}

$success = $path->Append('|Expiration');
if ($success != 1) {
    print 'Could not build credential path.' . "\n";
    exit;
}

$expiration = $xmlToken->getChildContent($path->getAsString());
$stringCompare->SetString($expiration);
$stringMatch7 = $stringCompare->ContentsEqual('',1);
if (($xmlToken->LastMethodSuccess != 1) or ($stringMatch7 == 1)) {
    print 'Missing or empty Expiration.' . "\n";
    exit;
}

$expires = new COM("Chilkat.CkDateTime");
$now = new COM("Chilkat.CkDateTime");
$success = $expires->SetFromTimestamp($expiration);
if ($success != 1) {
    print 'Stored expiration is invalid.' . "\n";
    exit;
}

$success = $now->SetFromCurrentSystemTime();
if ($success != 1) {
    print 'Could not read current time.' . "\n";
    exit;
}

if ($expires->DiffSeconds($now) <= 60) {
    print 'Stored credentials are expired or expire within 60 seconds; obtain fresh credentials.' . "\n";
    exit;
}

//  This S3 region is independent of the region that issued the STS credentials.
$region = 'us-west-2';
$endpoint = new COM("Chilkat.StringBuilder");
$endpoint->Append('s3.');
$endpoint->Append($region);
$endpoint->Append('.amazonaws.com');
$aws = new COM("Chilkat.AuthAws");
$aws->AccessKey = $accessKey;
$aws->SecretKey = $secretKey;
$aws->Region = $region;
$aws->ServiceName = 's3';
$aws->SignatureVersion = 4;
$rest = new COM("Chilkat.Rest");
$rest->ConnectTimeoutMs = 20000;
$rest->IdleTimeoutMs = 60000;
$rest->VerboseLogging = 0;
$success = $rest->SetAuthAws($aws);
if ($success != 1) {
    print 'Could not configure request signing.' . "\n";
    exit;
}

//  Keep this verified Socket alive while Rest uses its connection.
$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;
}

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

$xml = new COM("Chilkat.Xml");
$xml->Strict = 1;

$seenTokens = new COM("Chilkat.Hashtable");
$continuation = '';

$page = 0;

$more = 1;
while (($more == 1)) {
    if ($page == 10000) {
        print 'Page bound reached; bucket enumeration is incomplete.' . "\n";
        exit;
    }

    $success = $now->SetFromCurrentSystemTime();
    if ($success != 1) {
        print 'Could not read current time.' . "\n";
        exit;
    }

    if ($expires->DiffSeconds($now) <= 60) {
        print 'Credentials are expiring; obtain fresh credentials before continuing the listing.' . "\n";
        exit;
    }

    $page = $page + 1;
    $success = $rest->ClearAllQueryParams();
    if ($success != 1) {
        print 'Could not clear parameters from the previous page.' . "\n";
        exit;
    }

    //  All three credential components are required. Never log this signed URL.
    $success = $rest->AddQueryParam('X-Amz-Security-Token',$sessionToken);
    if ($success != 1) {
        print 'Could not set X-Amz-Security-Token.' . "\n";
        exit;
    }

    $success = $rest->AddQueryParam('max-buckets','100');
    if ($success != 1) {
        print 'Could not set max-buckets.' . "\n";
        exit;
    }

    $stringCompare->SetString($continuation);
    $stringMatch8 = $stringCompare->ContentsEqual('',1);
    if ($stringMatch8 != 1) {
        $success = $rest->AddQueryParam('continuation-token',$continuation);
        if ($success != 1) {
            print 'Could not set continuation-token.' . "\n";
            exit;
        }

    }

    $responseXml = $rest->fullRequestNoBody('GET','/');
    if ($rest->LastMethodSuccess != 1) {
        print 'S3 request did not complete; enumeration is incomplete.' . "\n";
        exit;
    }

    $success = $xml->LoadXml($responseXml);
    if ($rest->ResponseStatusCode != 200) {
        print 'S3 HTTP status: ' . $rest->ResponseStatusCode . "\n";
        if ($success == 1) {
            $value = $xml->getChildContent('Code');
            if ($xml->LastMethodSuccess == 1) {
                print 'AWS error code: ' . $value . "\n";
            }

            $value = $xml->getChildContent('RequestId');
            if ($xml->LastMethodSuccess == 1) {
                print 'AWS request ID: ' . $value . "\n";
            }

        }

        exit;
    }

    if ($success != 1) {
        print 'Invalid S3 XML response.' . "\n";
        exit;
    }

    $stringCompare->SetString($xml->Tag);
    $stringMatch9 = $stringCompare->ContentsEqual('ListAllMyBucketsResult',1);
    if ($stringMatch9 != 1) {
        print 'Unexpected S3 response root.' . "\n";
        exit;
    }

    if ($xml->HasChildWithTag('Buckets') != 1) {
        print 'Missing Buckets collection.' . "\n";
        exit;
    }

    $index = 0;
    while (($index < $xml->NumChildrenAt('Buckets'))) {
        $xml->I = $index;
        $value = $xml->getChildContent('Buckets|Bucket[i]|Name');
        $stringCompare->SetString($value);
        $stringMatch10 = $stringCompare->ContentsEqual('',1);
        if (($xml->LastMethodSuccess != 1) or ($stringMatch10 == 1)) {
            print 'Missing or empty Buckets|Bucket[i]|Name.' . "\n";
            exit;
        }

        print 'Bucket: ' . $value . "\n";
        $index = $index + 1;
    }

    $continuation = '';
    if ($xml->HasChildWithTag('ContinuationToken') == 1) {
        $continuation = $xml->getChildContent('ContinuationToken');
        if ($xml->LastMethodSuccess != 1) {
            print 'Invalid continuation token.' . "\n";
            exit;
        }

    }

    $more = 0;
    $stringCompare->SetString($continuation);
    $stringMatch11 = $stringCompare->ContentsEqual('',1);
    if ($stringMatch11 != 1) {
        if ($seenTokens->Contains($continuation) == 1) {
            print 'Repeated continuation token; enumeration is incomplete.' . "\n";
            exit;
        }

        $success = $seenTokens->AddStr($continuation,'seen');
        if ($success != 1) {
            print 'Could not track pagination.' . "\n";
            exit;
        }

        $more = 1;
    }

}

print 'Bucket enumeration complete.' . "\n";

?>