13
votes

I using the Amazon SDK for PHP and trying to set Cache-control Header on the image. When I try to add it via MetaData = array("Cache-Control") it changes it to be x-amz-meta-cache-control when I login to the S3 bucket, and when I download the file, there is no Cache-control set. But if I manually change this setting, the Cache-control works perfectly. Is there some parameter I missing that I can use to set HTTP Request Headers programmatically on upload? I'm using the PutObject method. I believe the AWS SDK is from 2013.

2
Can you please flag my answer as "accepted" if it helped you.Scuzzy

2 Answers

25
votes

The cache control isn't set via the "MetaData" index, "CacheControl" is at the same level as "MetaData", not contained within it.

http://docs.aws.amazon.com/aws-sdk-php-2/latest/class-Aws.S3.S3Client.html#_putObject

You'd use something like this as your configuration array for the putObject() method...

$s3client->putObject(array(
  'Bucket' => '...',
  'key' => '...',
  'body' => '...',
  'CacheControl' => 'max-age=172800',
  'MetaData' => array(
    'metaKey' => 'metaValue',
    'metaKey' => 'metaValue'
)));

For the upload() method...

$s3client->upload(
  'bucket',
  'key',
  fopen('sourcefile','r'),
  'public-read',
  array('params' => array(
    'CacheControl' => 'max-age=172800',
    'Metadata' => array(
      'metaKey' => 'metaValue',
      'metaKey' => 'metaValue'
))));

Also, it's worth pointing out that upload() will wrap putObject() for files of 5MB in size, otherwise it will initiate a multipart upload request.

15
votes

If you want to add the CacheControl header to an item already in your bucket, use the SDK's copyObject method. Set the MetadataDirective param to REPLACE to make the item overwrite itself.

I noticed one weird thing: I had to set the ContentType header too, even though it was already set. Otherwise the image would not display inline in the browser but be offered as a download.

$result = $s3->copyObject(array(
    'ACL' => 'public-read',
    'Bucket' => $bucket, // target bucket
    'CacheControl' => 'public, max-age=86400',
    'ContentType' => 'image/jpeg', // !!
    'CopySource' => urlencode($bucket . '/' . $key),
    'Key' => $key, // target file name
    'MetadataDirective' => 'REPLACE'
));