Skip to content

Instantly share code, notes, and snippets.

@cointilt
Created February 10, 2012 00:07
Show Gist options
  • Save cointilt/1784605 to your computer and use it in GitHub Desktop.
Save cointilt/1784605 to your computer and use it in GitHub Desktop.
AWS CloudFront Invalidation
<?php
class CloudFront
{
private static $access_key = '';
private static $secret_key = '';
private static $distribution = '';
private static $files = array();
private static $_error = array();
public function invalidate ( $files )
{
self::add_file ( $files );
$epoch = date('U');
$xml = '<InvalidationBatch>';
foreach ( self::$files as $file )
{
$xml .= '<Path>{$file}</Path>';
}
$xml .= '<CallerReference>{$distribution}{$epoch}</CallerReference></InvalidationBatch>';
$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: cloudfront.amazonaws.com\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://cloudfront.amazonaws.com', 443, $errno, $errstr, 30 );
if ( ! $fp )
{
self::_add_error ( "Connection failed: {$errno} {$errstr}\n" );
return false;
}
fwrite ( $fp, $msg );
$resp = '';
while ( ! feof ( $fp ) )
{
$resp .= fgets ( $fp, 1024 );
}
fclose ( $fp );
return true;
}
public function add_file ( $file )
{
if ( is_array ( $file ) )
{
array_merge ( self::$files, $file );
}
else
{
self::$files[] = $file;
}
}
public function access_key ( $val )
{
self::$access_key ( $val );
}
public function secret_key ( $val )
{
self::$secret_key ( $val );
}
public function distribution ( $val )
{
self::$distribution ( $val );
}
private function _clear_files()
{
self::$files = array();
}
private function _add_error ( $error )
{
self::$_error[] = $error;
}
public function get_errors()
{
return self::$_error;
}
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment