我写了一个小而肯定可以改进的 php 脚本,它正是为这个目的服务的。它使用给定的凭据(用户电子邮件和 API 密钥)连接到 Cloudflare 的 API。要检索 API 密钥:
登录到 Cloudflare 帐户。
转到我的个人资料。
向下滚动到 API Keys 并找到 Global API Key。
单击 API 密钥以查看您的 API 标识符。
在第一步中,脚本会查询所谓的 Zone-ID,它是您要控制的域的唯一标识符。由于迄今为止 Cloudflare 没有提供在其后端查看此 ID 的选项,因此只能通过 API 请求获取。
在第二步中,我们再次连接到 Cloudflare 的 API,这一次指示清除该区域的整个缓存。
这是我的解决方案(我把它放在我的插件更新脚本的底部,在其他一切都完成后运行):
<?php
//Credentials for Cloudflare
$cust_email = ''; //user@domain.tld
$cust_xauth = ''; //retrieved from the backend after loggin in
$cust_domain = ''; //domain.tld, the domain you want to control
if($cust_email == "" || $cust_xauth == "" || $cust_domain == "") return;
//Get the Zone-ID from Cloudflare since they don't provide that in the Backend
$ch_query = curl_init();
curl_setopt($ch_query, CURLOPT_URL, "https://api.cloudflare.com/client/v4/zones?name=".$cust_domain."&status=active&page=1&per_page=5&order=status&direction=desc&match=all");
curl_setopt($ch_query, CURLOPT_RETURNTRANSFER, 1);
$qheaders = array(
'X-Auth-Email: '.$cust_email.'',
'X-Auth-Key: '.$cust_xauth.'',
'Content-Type: application/json'
);
curl_setopt($ch_query, CURLOPT_HTTPHEADER, $qheaders);
$qresult = json_decode(curl_exec($ch_query),true);
curl_close($ch_query);
$cust_zone = $qresult['result'][0]['id'];
//Purge the entire cache via API
$ch_purge = curl_init();
curl_setopt($ch_purge, CURLOPT_URL, "https://api.cloudflare.com/client/v4/zones/".$cust_zone."/purge_cache");
curl_setopt($ch_purge, CURLOPT_CUSTOMREQUEST, "DELETE");
curl_setopt($ch_purge, CURLOPT_RETURNTRANSFER, 1);
$headers = [
'X-Auth-Email: '.$cust_email,
'X-Auth-Key: '.$cust_xauth,
'Content-Type: application/json'
];
$data = json_encode(array("purge_everything" => true));
curl_setopt($ch_purge, CURLOPT_POST, true);
curl_setopt($ch_purge, CURLOPT_POSTFIELDS, $data);
curl_setopt($ch_purge, CURLOPT_HTTPHEADER, $headers);
$result = json_decode(curl_exec($ch_purge),true);
curl_close($ch_purge);
//Tell the user if it worked
if($result['success']==1) echo "Cloudflare Cache successfully purged! Changes should be visible right away.<br>If not try clearing your Browser Cache by pressing \"Ctrl+F5\"";
else echo "Error purging Cloudflare Cache. Please log into Cloudflare and purge manually!";
?>