Amazon CloudFront – PHP Invalidator

cloudfrontlogoAmazon recently (finally!) added support for invalidation to CloudFront.  Frankly, without this feature the service was pretty useless to me since updating (or deleting) the cached resource would mean that the actual operation would take up to 24 hours to be reflected on the CDN.  But all is well now as the invalidation API available and is, as expected, very responsive.  (Based on initial tests, invalidations take a few minutes to process.)

What was missing though is a PHP API for easily creating and processing invalidation requests, so I put one together, largely inspired by the existing S3 and CloudFront PHP kits.


To invalidate an object, just create an instance of CloudFront and call invalidate() it. Like so:

[code language="php"]
$cf = new CloudFront($keyId, $secretKey, $distributionId);

// invalidate single object
$cf->invalidate("/path/to/object");

// invalidate many objects with single (batch) request
$cf->invalidate(array("/path/to/first","/path/to/second"));

// enable debugging (response output) by passing true as the second argument
$cf->invalidate(array("/path/to/first","/path/to/second"), true);[/code]

Check out the source on GitHub: http://github.com/subchild/CloudFront-PHP-Invalidator

A couple of things to keep in mind. CloudFront supports very few concurrent invalidation requests so make batch requests as much as possible.  If you absolutely need to up this limit, go to http://aws.amazon.com/cloudfront-request/ and submit such a request. Also, keep in mind that updating a resource on CloudFront means that you’ll need to update it on S3 first, then invalidate the CloudFront copy only after the S3 has actually been updated, not when you make the request.