How to Clear CloudFlare Caches of Multiple URLs using PHP Script with CloudFlare API?


The CloudFlare allows you to purge manually up to 30 URLs at a time if you navigate Caching Tab.

cloudflare-purge-individual-files How to Clear CloudFlare Caches of Multiple URLs using PHP Script with CloudFlare API? API cache cloud cloudflare CloudFlare php PHP programming languages

cloudflare-purge-individual-files

You could also, purge all URLs which is known as “Purge Everything” but this isn’t recommended because that the cache miss if multiple requests hit at the same time, which could overload your server.

cloudflare-purge-everything How to Clear CloudFlare Caches of Multiple URLs using PHP Script with CloudFlare API? API cache cloud cloudflare CloudFlare php PHP programming languages

cloudflare-purge-everything

Using CloudFlare APIs to Purge Cache Programmatically

Using CloudFlare APIs, we can do this in a script and this is beneficial if you have usually many many URLs to purge if e.g. a post is published, a feature is updated.

Getting the Zone ID

You will first need to get the Zone ID. A Zone is basically a domain. The CloudFlare API for this purpose is documented here and example output is JSON which looks like:

cloudflare-get-zone-id How to Clear CloudFlare Caches of Multiple URLs using PHP Script with CloudFlare API? API cache cloud cloudflare CloudFlare php PHP programming languages

cloudflare-get-zone-id json response

We can then write a PHP function to do this:

1
2
3
4
5
6
7
function getZones($key, $email, $page = 1, $per_page = 100) {
  $cmd = 'curl -s -X GET "https://api.cloudflare.com/client/v4/zones?'.
        'status=active&page=$page&per_page=$per_page&order=status&direction=desc&match=all" -H "X-Auth-Email: '.$email.
        '" -H "X-Auth-Key: '.$key.
        '" -H "Content-Type: application/json"';
  return json_decode(shell_exec($cmd));
}  
function getZones($key, $email, $page = 1, $per_page = 100) {
  $cmd = 'curl -s -X GET "https://api.cloudflare.com/client/v4/zones?'.
        'status=active&page=$page&per_page=$per_page&order=status&direction=desc&match=all" -H "X-Auth-Email: '.$email.
        '" -H "X-Auth-Key: '.$key.
        '" -H "Content-Type: application/json"';
  return json_decode(shell_exec($cmd));
}  

The input parameters are the APP_KEY and the account email address. The default is to return the first 100 zone records, which should be enough for most cases. We use the function shell_exec to execute the external command but you could also use a safer approach which is the php_curl function.

Purge URL Cache

With the Domain (Zone) ID, you can then use the second API, which is to delete an array of URLs up to 30. The official cloudflare API for this is documented here.

cloudflare-curl-purge-cache-example How to Clear CloudFlare Caches of Multiple URLs using PHP Script with CloudFlare API? API cache cloud cloudflare CloudFlare php PHP programming languages

cloudflare-curl-purge-cache-example

PHP Script to Purge CloudFlare Caches for Multiple URLs

With above two, we can have the following PHP function to purge the cloudflare caches for several URLs at once:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
// $arr = array of URLs
// $key = APP_KEY
// $email = account email
// $data = the result of getZones($key, $email)
function removeCache($arr, $key, $email, $data) {
  if (!$data) {
      throw new Exception("data null");
  }
  $ok = $data->success ?? false;
  if (!$ok) {
      throw new Exception("not success" . ($data->errors ?? '') . ($data->messages ?? ''));
  }   
  $result = $data->result ?? null;
  if (!$result) {
      throw new Exception("result null");
  }  
  $zones = array();          
  foreach ($arr as $url) {
      $domain = parse_url($url)['host'];
      $id = '';
      // the zone id should be cached  
      if (array_key_exists($domain, $zones)) {
          $id = $zones[$domain];
      } else {
        foreach ($result as $tmp) {
          if ($tmp->name == $domain) {
            $id = $tmp->id;
            $zones[$domain] = $id; 
          }
        }
      } 
      if ($id == '') {
        throw new Exception("$domain not found");
      }
      $cmd = "curl -s -X DELETE \"https://api.cloudflare.com/client/v4/zones/$id/purge_cache\" -H \"X-Auth-Email: $email\" -H \"X-Auth-Key: $key\" -H \"Content-Type: application/json\" --data '{\"files\":[\"$url\"]}'";
      $r = shell_exec($cmd);
      $rr = json_decode($r, false);
      if (!$rr) {
        throw new Exception("failure: $r");
      }
      if (!isset($rr->success)) {
        throw new Exception($rr->errors . '  ' . $rr->messages);
      }
      echo "Cache Removed:  $url  \n";
  }
}
// $arr = array of URLs
// $key = APP_KEY
// $email = account email
// $data = the result of getZones($key, $email)
function removeCache($arr, $key, $email, $data) {
  if (!$data) {
      throw new Exception("data null");
  }
  $ok = $data->success ?? false;
  if (!$ok) {
      throw new Exception("not success" . ($data->errors ?? '') . ($data->messages ?? ''));
  }   
  $result = $data->result ?? null;
  if (!$result) {
      throw new Exception("result null");
  }  
  $zones = array();          
  foreach ($arr as $url) {
      $domain = parse_url($url)['host'];
      $id = '';
      // the zone id should be cached  
      if (array_key_exists($domain, $zones)) {
          $id = $zones[$domain];
      } else {
        foreach ($result as $tmp) {
          if ($tmp->name == $domain) {
            $id = $tmp->id;
            $zones[$domain] = $id; 
          }
        }
      } 
      if ($id == '') {
        throw new Exception("$domain not found");
      }
      $cmd = "curl -s -X DELETE \"https://api.cloudflare.com/client/v4/zones/$id/purge_cache\" -H \"X-Auth-Email: $email\" -H \"X-Auth-Key: $key\" -H \"Content-Type: application/json\" --data '{\"files\":[\"$url\"]}'";
      $r = shell_exec($cmd);
      $rr = json_decode($r, false);
      if (!$rr) {
        throw new Exception("failure: $r");
      }
      if (!isset($rr->success)) {
        throw new Exception($rr->errors . '  ' . $rr->messages);
      }
      echo "Cache Removed:  $url  \n";
  }
}

Now, you can just call the example like this:

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
$data = getZones($key, $email);
removeCache([
                "https://helloacm.com",
                "https://helloacm.com/sitemap.xml",
                "https://helloacm.com/archives-of-pagesposts",
                "https://helloacm.com/top",
                "https://helloacm.com/robots.txt",
                "https://helloacm.com/feed",
                "https://helloacm.com/page/2",
                "https://helloacm.com/page/3",
                "https://helloacm.com/page/4",
                "https://helloacm.com/page/5"
              ], 
              $key, $email, $data
); 
$data = getZones($key, $email);
removeCache([
                "https://helloacm.com",
                "https://helloacm.com/sitemap.xml",
                "https://helloacm.com/archives-of-pagesposts",
                "https://helloacm.com/top",
                "https://helloacm.com/robots.txt",
                "https://helloacm.com/feed",
                "https://helloacm.com/page/2",
                "https://helloacm.com/page/3",
                "https://helloacm.com/page/4",
                "https://helloacm.com/page/5"
              ], 
              $key, $email, $data
); 

CloudFlare Technology

–EOF (The Ultimate Computing & Technology Blog) —

GD Star Rating
loading...
888 words
Last Post: How to Unlock QuickHostUK VPS Network Speed to 1GHz?
Next Post: When x==x Evaluates to FALSE in C/C++?

The Permanent URL is: How to Clear CloudFlare Caches of Multiple URLs using PHP Script with CloudFlare API?

Leave a Reply