Reputation: 4300
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
Upvotes: 3
Views: 1517
Reputation: 138
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": [[]]
}
}
}
Upvotes: 3
Reputation: 4300
One solution doesn't seem like the most efficient way, but it works - it works off the fact that get_headers($fullurl)
works.
Since we need to sometimes access private files, we can get a presigned URL that will give any user with the URL access, and run get_headers()
off of that.
$s3getobject = $s3->getCommand('GetObject', [
'Bucket' => 'my-files',
'Key' => $filepath
]);
$presignedrequest = $s3->createPresignedRequest($s3getobject, '+5 minutes');
$s3url = (string) $presignedrequest->getUri();
$headers = get_headers($s3url, true);
Upvotes: -1