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

S3: List Objects Under a Prefix

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 S3_ListBucketObjects with list-type=2 to request ListObjectsV2. Follows opaque NextContinuationToken values while IsTruncated is true, including empty pages; detects missing/repeated tokens and stops at 10,000 pages with incomplete-results status. Requires s3:ListBucket.

Requests encoding-type=url so keys containing XML-incompatible characters can be represented. Decode returned keys exactly once before reusing them. Query values are encoded separately. Sizes remain decimal strings to preserve large values; LastModified is an ISO 8601 UTC timestamp, not RFC 822. Owner.DisplayName is not used. Listing pages are not a single snapshot if objects change during enumeration.

A prefix is a key-name filter, not a filesystem folder. The trailing slash matters: images/ excludes keys such as images-old/file.jpg. Without a delimiter, all matching descendant keys are included.

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';
$bucketPath = new COM("Chilkat.StringBuilder");
$encoded = new COM("Chilkat.StringBuilder");
$xml = new COM("Chilkat.Xml");
$seenTokens = new COM("Chilkat.Hashtable");
$token = '';
$more = 1;
$page = 0;
$prefix = 'images/';
while (($more == 1)) {
    if ($page == 10000) {
        print 'Page limit reached; listing is incomplete.' . "\n";
        exit;
    }

    $page = $page + 1;
    $bucketPath->SetString($bucketName);
    $bucketPath->Append('?list-type=2&max-keys=1000&encoding-type=url');
    $encoded->SetString($prefix);
    $bucketPath->Append('&prefix=');
    $bucketPath->Append($encoded->getEncoded('url','utf-8'));
    $stringCompare->SetString($token);
    $stringMatch4 = $stringCompare->ContentsEqual('',1);
    if ($stringMatch4 != 1) {
        $encoded->SetString($token);
        $bucketPath->Append('&continuation-token=');
        $bucketPath->Append($encoded->getEncoded('url','utf-8'));
    }

    $xmlStr = $http->s3_ListBucketObjects($bucketPath->getAsString());
    if ($http->LastMethodSuccess != 1) {
        print 'Request failed (transport or S3 error). HTTP status: ' . $http->LastStatus . "\n";
        //  Inspect LastErrorText privately. Do not log credentials or signed URLs.
        exit;
    }

    if ($http->LastStatus != 200) {
        print 'Unexpected HTTP status: ' . $http->LastStatus . "\n";
        exit;
    }

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

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

    $stringCompare->SetString($xml->getChildContent('EncodingType'));
    $stringMatch6 = $stringCompare->ContentsEqual('url',1);
    if ($stringMatch6 != 1) {
        print 'Expected URL-encoded listing keys.' . "\n";
        exit;
    }

    $i = 0;
    $count = $xml->NumChildrenHavingTag('Contents');
    while (($i < $count)) {
        $xml->I = $i;
        //  Decode keys exactly once. Sizes remain decimal strings (not int).
        $itemKey = $http->urlDecode($xml->getChildContent('Contents[i]|Key'));
        $stringCompare->SetString($itemKey);
        $stringMatch7 = $stringCompare->ContentsEqual('',1);
        if (($http->LastMethodSuccess != 1) or ($stringMatch7 == 1)) {
            print 'Invalid object key.' . "\n";
            exit;
        }

        $size = $xml->getChildContent('Contents[i]|Size');
        $stringCompare->SetString($size);
        $stringMatch8 = $stringCompare->ContentsEqual('',1);
        if (($xml->LastMethodSuccess != 1) or ($stringMatch8 == 1)) {
            print 'Incomplete object entry.' . "\n";
            exit;
        }

        $modified = $xml->getChildContent('Contents[i]|LastModified');
        $stringCompare->SetString($modified);
        $stringMatch9 = $stringCompare->ContentsEqual('',1);
        if (($xml->LastMethodSuccess != 1) or ($stringMatch9 == 1)) {
            print 'Incomplete object entry.' . "\n";
            exit;
        }

        print 'Key: ' . $itemKey . "\n";
        print 'Bytes: ' . $size . "\n";
        //  S3 returns ISO 8601, not RFC 822. Keep the original UTC timestamp.
        print 'Last modified (UTC): ' . $modified . "\n";
        $i = $i + 1;
    }

    $truncated = $xml->getChildContent('IsTruncated');
    $stringCompare->SetString($truncated);
    $stringMatch10 = $stringCompare->ContentsEqual('true',1);
    $stringCompare->SetString($truncated);
    $stringMatch11 = $stringCompare->ContentsEqual('false',1);
    if (($stringMatch10 != 1) and ($stringMatch11 != 1)) {
        print 'Missing or invalid IsTruncated; listing is incomplete.' . "\n";
        exit;
    }

    $more = 0;
    $stringCompare->SetString($truncated);
    $stringMatch12 = $stringCompare->ContentsEqual('true',1);
    if ($stringMatch12 == 1) {
        $token = $xml->getChildContent('NextContinuationToken');
        $stringCompare->SetString($token);
        $stringMatch13 = $stringCompare->ContentsEqual('',1);
        if (($xml->LastMethodSuccess != 1) or ($stringMatch13 == 1)) {
            print 'Missing continuation token; listing is incomplete.' . "\n";
            exit;
        }

        if ($seenTokens->Contains($token) == 1) {
            print 'Repeated continuation token; listing is incomplete.' . "\n";
            exit;
        }

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

        $more = 1;
    }

}

print 'Object listing complete.' . "\n";

?>