Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Retrieving headers for streaming object using AWS SDK for PHP (v3)

A guide exists for v2 of the AWS SDK for PHP to stream objects, like an image, from S3. In that guide, it references $command->getResponse()->getHeaders() - both getResponse() and getHeaders() do not seem to exist in v3 of the SDK.

The documentation for the stream wrapper in v3 makes no reference to retrieving the headers. I've tried the native PHP get_headers() with the s3:// path, but that returns false (no errors). If I try get_headers($fullurl), I am able to retrieve the headers.

How can I retrieve the headers for the object using the streaming path s3:// for version 3 of the AWS SDK for PHP? Using the full URL will work for scenarios where I have private files.

Running some of the other native PHP functions that the documentation references do correctly return values using the s3:// path. There might be a SDK method call for the headers, I just can't find it.

$s3->registerStreamWrapper();

$headers = get_headers('s3://my-files/' . $filepath);
//$headers === false

$headers = get_headers('http://my-files.s3.amazonaws.com/' . $filepath);
//$headers correctly retrieves all the headers
like image 565
Luke Shaheen Avatar asked Sep 02 '26 15:09

Luke Shaheen


1 Answers

v2 code:

$command = $s3->getCommand('HeadObject', [
    'Bucket' => $bucket,
    'Key'    => $key,
]);

$headers = $command->getResponse()->getHeaders();

v3 code:

$command = $s3->getCommand('HeadObject', [
    'Bucket' => $bucket,
    'Key'    => $key,
]);

$result = $s3->execute($command);
$headers = $result->get("@metadata")['headers'];

It's not quite a drop-in replacement. The array keys are lowercase now so you'll have to convert references like $headers['Last-Modified'] to $headers['last-modified']

I couldn't find this in docs. I saw the examples using execute/results so I ran echo $result to look at the new structure and saw @metadata. It looks like this:

{
    .........
    "@metadata": {
        "statusCode": 200,
        "effectiveUri": "https:\/\/example.s3.amazonaws.com\/example\/file.txt",
        "headers": {
            "x-amz-id-2": "",
            "x-amz-request-id": "",
            "date": "Tue, 15 Oct 2019 20:04:18 GMT",
            "x-amz-replication-status": "COMPLETED",
            "last-modified": "Tue, 15 Oct 2019 19:08:28 GMT",
            "etag": "",
            "x-amz-server-side-encryption": "AES256",
            "x-amz-version-id": "",
            "accept-ranges": "bytes",
            "content-type": "application\/octet-stream",
            "content-length": "32213",
            "server": "AmazonS3"
        },
        "transferStats": {
            "http": [[]]
        }
    }
}
like image 65
Maave Avatar answered Sep 05 '26 04:09

Maave



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!