So I have setup a function that call to the cloudflare api and grabs the page views from each of my websites on cloudflare. I've been having an issue where half the time the api loads it will load the correct numbers, the other half it will just return Null or an empty string. I can't figure out if its an api issue or if its got something to do with my code. I also am wondering if there is a way I can just check if value is null and retry the api call until it returns a value but that's a last case scenario and I'm not sure how to go about it. I am using the codeigniter framework.
My API library function:
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;
}
And here is the function that calls for each api then cache's them:
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'));
}
It either returns this:
array(2) {
["site1"]=>
int(2088)
["site2"]=>
int(4117)
}
or the values will be null.