Kirk Beard Kirk Beard - 4 months ago 21
PHP Question

How to set Content-Disposition with AWS PHP SDK v2 and CopyObject?

I'm using the AWS PHP SDK v2.x to copy objects between S3 buckets using the following code:

try {
'Bucket' => $target_bucket,
'Key' => $target_key,
'CopySource' => $source_bucket . '/' . $source_key,
'Content-Disposition' => 'attachment',
//'Content-Disposition' => 'attachment; filename="' . basename($target_key) . '"'
//'ContentDisposition' => 'attachment'
//'ContentDisposition' => 'attachment; filename="' . basename($target_key) . '"'
} catch (Aws\S3\Exception\S3Exception $e) {
echo 'error';

The file is copied to the S3 bucket without any errors, but I'm unable to set the the
in order to force the browser to download the file rather than stream it. I've tried a few options (commented out above) but nothing seem to work.

I've even attempted to pass the value in the
array even though the documentation says otherwise but the AWS Console lists the
under the Metadata section.

If I manually change the
in the AWS Console then the browser downloads the file as expected.

So, how can I pass the value to the S3 object correctly? Can I pass it at all using the


The CopyObject operation is tricky, IMO. I think the missing piece of the puzzle for you is the MetadataDirective parameter. Try the following:

    'Bucket'     => $target_bucket,
    'Key'        => $target_key,
    'CopySource' => $source_bucket . '/' . $source_key,
    'ContentDisposition' => 'attachment; filename="'.basename($target_key).'"',
    'MetadataDirective'  => 'REPLACE',

Note: The code is in this post is also licensed under version 2.0 of the Apache License.