Problem :- How to add caching headers to an existing amazon S3 object?
Background:- Yes, I know. I should have done it when I had uploaded those files. However they are already there and now we need to add caching control headers to our already uploaded objects.
Simple solution :- Use cloud Berry explorer or some such tool.
Programmer's solution:- Looks like using aws-sdk copy_object does the trick.
Code sample
error_reporting(-1);
require_once 'sdk.class.php';
// copy S3 object
// Instantiate the AmazonS3 class
$options = array("key" => "aws-key" , "secret" => "aws-secret") ;
$s3 = new AmazonS3($options);
$bucket = "bucket.3mik.com" ;
$exists = $s3->if_bucket_exists($bucket);
if(!$exists) {
trigger_error("S3 bucket does not exists \n" , E_USER_ERROR);
}
$name = "cows-and-aliens.jpg" ;
echo " change headers for $name \n" ;
$source = array("bucket" => $bucket, "filename" => $name);
$dest = array("bucket" => $bucket, "filename" => $name);
//caching headers
$offset = 3600*24*365;
$expiresOn = gmdate('D, d M Y H:i:s \G\M\T', time() + $offset);
$headers = array('Expires' => $expiresOn, 'Cache-Control' => 'public, max-age=31536000');
$meta = array('acl' => AmazonS3::ACL_PUBLIC, 'headers' => $headers);
$response = $s3->copy_object($source,$dest,$meta);
if($response->isOk()){
printf("copy object done \n" );
}else {
printf("Error in copy object \n" );
}