Skip to content

Instantly share code, notes, and snippets.

@maciekmm
Created June 7, 2017 07:09
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save maciekmm/eb52c546cde3af51331988aacc02838e to your computer and use it in GitHub Desktop.
Save maciekmm/eb52c546cde3af51331988aacc02838e to your computer and use it in GitHub Desktop.
Cloudflare cache purging script meant to be attached to github repo via a page_built webhook.
<?php
error_reporting(0);
define("CF_ZONE_ID", "");
define("CF_EMAIL", "");
define("CF_API_KEY", "");
define("GH_SECRET", "");
if($_SERVER['REQUEST_METHOD'] !== 'POST') {
error_log("Invalid request (expected POST)");
http_response_code(400);
exit("Invalid request");
}
$payload = file_get_contents('php://input');
//secret verification
if("sha1=".hash_hmac("sha1",$payload,GH_SECRET) !== $_SERVER['HTTP_X_HUB_SIGNATURE']) {
error_log("Invalid secret, ".$_SERVER['HTTP_X_HUB_SIGNATURE']);
http_response_code(400);
exit("Invalid secret");
}
$decoded = json_decode($payload);
if($decoded->build->status !== 'built') {
error_log("Page not built");
exit("Page not built");
}
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, "https://api.cloudflare.com/client/v4/zones/".CF_ZONE_ID."/purge_cache");
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_setopt($ch, CURLOPT_POSTFIELDS, "{\"purge_everything\":true}");
curl_setopt($ch, CURLOPT_HTTPHEADER, array('X-Auth-Email: '.CF_EMAIL, 'X-Auth-Key: '.CF_API_KEY, 'Content-Type: application/json'));
$result = curl_exec($ch);
$result = json_decode($result);
curl_close($ch);
if($result->success !== true) {
error_log("Request did not succeed.".json_encode($result));
exit("Request error");
}
echo("Cache purged");
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment