Last active
August 7, 2023 09:23
-
-
Save Greg-Boggs/73796406278cd67334db08dc052931dd to your computer and use it in GitHub Desktop.
PHP code to Purge Cloudflare Cache
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?php | |
// Replace EMAIL/API_KEY/ZONE_ID with your details. | |
// Zone ID is on the dashboard for the domain in the bottom right. | |
// Api keys are generated from the account settings. You must give cache purge permissions | |
// Place this script on your webserver and point a Github Webhook at it, and you'll clear | |
// the Cloudflare cache every time you do a push to GH. | |
$zoneId = "xxx"; | |
$apiKey = "xxx"; | |
$email = "xxx"; | |
// optional URL for individual URL purge | |
$file = 'https://example.com/style.css'; | |
try { | |
$head = []; | |
$head[] = 'Content-Type: application/json'; | |
$head[] = "X-Auth-Email: $email"; | |
$head[] = "X-Auth-Key: $apiKey"; | |
$head[] = 'cache-control: no-cache'; | |
$url = "https://api.cloudflare.com/client/v4/zones/$zoneId/purge_cache"; | |
// You can also purge files like: | |
//$purge = ['files' => [$file]; | |
$purge = ['purge_everything' => true]; | |
$ch = curl_init(); | |
curl_setopt($ch, CURLOPT_URL, $url); | |
curl_setopt($ch, CURLOPT_CUSTOMREQUEST, "DELETE"); | |
curl_setopt($ch, CURLOPT_HTTPHEADER, $head); | |
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($purge)); | |
$result = curl_exec($ch); | |
$httpCode = curl_getinfo($ch, CURLINFO_HTTP_CODE); | |
curl_close($ch); | |
} catch (Exception $e) { | |
print($e); | |
} |
Please correct from file = 'https://example.com/style.css'; to $file = 'https://example.com/style.css';
Fixed
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
I updated the code in the gist Tapan-thapa! Thanks for posting. Lemme know if I missed anything.