Skip to content

Instantly share code, notes, and snippets.

What would you like to do?
How to invalidate items in AWS CloudFront
* Super-simple AWS CloudFront Invalidation Script
* Steps:
* 1. Set your AWS access_key
* 2. Set your AWS secret_key
* 3. Set your CloudFront Distribution ID
* 4. Define the batch of paths to invalidate
* 5. Run it on the command-line with: php cf-invalidate.php
* The author disclaims copyright to this source code.
* Details on what's happening here are in the CloudFront docs:
$access_key = 'AWS_ACCESS_KEY';
$secret_key = 'AWS_SECRET_KEY';
$distribution = 'DISTRIBUTION_ID';
$epoch = date('U');
$xml = <<<EOD
* You probably don't need to change anything below here.
$len = strlen($xml);
$date = gmdate('D, d M Y G:i:s T');
$sig = base64_encode(
hash_hmac('sha1', $date, $secret_key, true)
$msg = "POST /2010-11-01/distribution/{$distribution}/invalidation HTTP/1.0\r\n";
$msg .= "Host:\r\n";
$msg .= "Date: {$date}\r\n";
$msg .= "Content-Type: text/xml; charset=UTF-8\r\n";
$msg .= "Authorization: AWS {$access_key}:{$sig}\r\n";
$msg .= "Content-Length: {$len}\r\n\r\n";
$msg .= $xml;
$fp = fsockopen('ssl://', 443,
$errno, $errstr, 30
if (!$fp) {
die("Connection failed: {$errno} {$errstr}\n");
fwrite($fp, $msg);
$resp = '';
while(! feof($fp)) {
$resp .= fgets($fp, 1024);
echo $resp;
Copy link

Great work, Clay. Thanks! FYI - I forked this and created tweaked version of this excellent script which provides a simple way to invalidate a single file on CloudFront by using this script in a browser:

Copy link

claylo commented Sep 17, 2011

Steve, thanks for your tweak -- even more useful! Glad my script was able to give you a head start down that path. :)

Copy link

Thanks for this. Can't believe they don't have this avail in the console. Couple confusing points that could use a comment: required preceding slash in path of invalidation files, and the API date in the POST. I thought it needed to be the current date. Appreciate it!

Copy link

bgurupra commented May 2, 2014

Thanks for this. It was useful

Copy link

Very useful. Thank you very much!

Copy link

eduan commented Aug 18, 2015

Man... you deserve an ecological award to help me clean a ton of trash code

Copy link

ZE3kr commented Jan 28, 2017

Cool things! AWS SDK is too big and complex and I already give it up.

Copy link

Resvina commented Mar 31, 2017

Need help!

We are ruby bashed env. I'm looking for a bash script to do invalidation without having to use awscli. is there anything available?


Copy link

Suggest you use $epoch = date('Uu'); rather than $epoch = date('U'); - it adds microseconds, and means that if you're sending two invalidations in quick succession, one of them won't randomly break.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment