Skip to content

Instantly share code, notes, and snippets.

@DamianZaremba
Created May 31, 2013 00:34
Show Gist options
  • Save DamianZaremba/5682283 to your computer and use it in GitHub Desktop.
Save DamianZaremba/5682283 to your computer and use it in GitHub Desktop.
Github Pages, Cloudflare Cache Purge
<?php
// Cloudflare settings
$CF_API_TOKEN = "";
$CF_ZONE = "";
$CF_EMAIL = "";
// API key
$AUTHORIZATION_KEY = "";
// API Log
$API_LOG = "output.log";
// Github hook ips
$AUTHORIZED_IPS = array(
"204.232.175.64/27",
"192.30.252.0/22",
);
// Sanity checks
if($AUTHORIZATION_KEY) {
if(!array_key_exists('key', $_GET) ||
$_GET['key'] !== $AUTHORIZATION_KEY) {
die('Bad authorization key');
}
}
// Purge function
function purge_url($url) {
global $CF_API_TOKEN, $CF_ZONE, $CF_EMAIL;
$payload = array(
'a' => 'zone_file_purge',
'tkn' => $CF_API_TOKEN,
'email' => $CF_EMAIL,
'z' => $CF_ZONE,
'url' => $url,
);
$data = "";
foreach($payload as $key => $val) {
$data .= $key . '=' . urlencode($val) . '&';
}
rtrim($data, '&');
$ch = curl_init();
curl_setopt($ch,CURLOPT_URL, 'https://www.cloudflare.com/api_json.html');
curl_setopt($ch,CURLOPT_POST, count($payload));
curl_setopt($ch,CURLOPT_POSTFIELDS, $data);
curl_setopt($ch,CURLOPT_RETURNTRANSFER, true);
$result = curl_exec($ch);
curl_close($ch);
return $result;
}
if(count($AUTHORIZED_IPS) > 0) {
if(!array_key_exists('REMOTE_ADDR', $_SERVER)) {
die('Could not get IP');
}
$ip_match = False;
foreach($AUTHORIZED_IPS as $range) {
list($subnet, $mask) = explode('/', $range);
$ip = ip2long($_SERVER['REMOTE_ADDR']);
$subnet = ip2long($subnet);
$mask = -1 << (32 - $mask);
$subnet &= $mask;
if(($ip & $mask) === $subnet) {
$ip_match = True;
}
}
if(!$ip_match) {
die('Invalid IP');
}
}
// Get the json
if(!array_key_exists('payload', $_REQUEST)) {
die('No data passed');
}
$data = json_decode($_REQUEST['payload']);
if(!$data) {
die('Could not decode JSON');
}
if($data->ref != "refs/heads/master") {
die('Not on head');
}
if(!array_key_exists('commits', $data)) {
die('Commits not found');
}
$modified_files = array();
foreach($data->commits as $commit) {
$modified_files = array_merge($commit->added);
$modified_files = array_merge($modified_files, $commit->modified);
$modified_files = array_merge($modified_files, $commit->removed);
}
foreach($modified_files as $file) {
$url = "http://" . $CF_ZONE . "/" . $file;
$output = purge_url($url);
$fh = fopen($API_LOG, 'a');
fwrite($fh, "[" . date("d-m-Y H:i:s") . "] " . $output . "\n\n");
fclose($fh);
}
die('ok');
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment