因此,我设置了一个函数,该函数调用cloudflare api,并从我在cloudflare上的每个网站获取网页浏览量。我一直遇到一个问题,api加载的一半时间将加载正确的数字,另一半将仅返回Null或空字符串。我不知道它是否是api问题或它是否与我的代码有关。我也想知道是否有一种方法可以仅检查value是否为null并重试api调用,直到它返回一个值,但这是最后一种情况,并且我不确定该如何处理。我正在使用codeigniter框架。
我的API库函数:
public function get_page_views($zoneID)
{
$header = array(
'X-Auth-Email: my@email.com',
'X-Auth-Key: myAuthKey',
'Content-Type: application/json'
);
// Gathering all data within past year because thats what cloudflare limits me too.
$subtract = strtotime('-1 year');
$since = date('Y-m-d', $subtract);
$until = date('Y-m-d');
$data = json_decode($this->get_url_contents("https://api.cloudflare.com/client/v4/zones/". $zoneID ."/analytics/dashboard?since=". $since ."T00:00:00Z&until=". $until ."T00:00:00Z&continuous=true", $header), true);
return $data['result']['totals']['requests']['all'];
}
private function get_url_contents($url, $header)
{
ini_set('max_execution_time', 300);
$crl = curl_init();
$timeout = 5;
curl_setopt ($crl, CURLOPT_URL,$url);
curl_setopt ($crl, CURLOPT_RETURNTRANSFER, 1);
curl_setopt ($crl, CURLOPT_CONNECTTIMEOUT, $timeout);
curl_setopt ($crl, CURLOPT_HTTPHEADER, $header);
curl_setopt($crl, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($crl, CURLOPT_TIMEOUT, 50000);
$ret = curl_exec($crl);
curl_close($crl);
return $ret;
}
这是调用每个api然后缓存它们的函数:
public function fetch_pageViews()
{
$cache = array(
'site1' => $this->api->get_page_views('myZoneID'),
'site2' => $this->api->get_page_views('myZoneID'),
);
$this->cache->file->save('pageViews', $cache, 0);
var_dump($this->cache->file->get('pageViews'));
}
它要么返回此:
array(2) {
["site1"]=>
int(2088)
["site2"]=>
int(4117)
}
否则值将为空。