Advertisement
Not a member of Pastebin yet?
Sign Up,
it unlocks many cool features!
- // lets define the working files
- define("FILE_API_TIMESTAMP", "api.timestamp.txt");
- define("FILE_API_DATA", "api.data.json");
- // initialize main vars
- // last api call
- $last_call = 0;
- // latest api data
- $api_data = false;
- // this moment timestamp
- $current_time = time();
- // check last api call from saved file
- if (file_exists(FILE_API_TIMESTAMP)) {
- $last_call = floatval( file_get_contents( FILE_API_TIMESTAMP ) );
- }
- // if more than 60 seconds passed since last call,
- // call API then save results
- if ($current_time - $last_call > 60) {
- // get new data
- // $api_data = getApiData(); -> put your function here: Curl etc...
- $api_data = "new data: ".time(); // just an example
- if ($api_data) {
- // if new data is available,
- // - log the current timestamp
- file_put_contents(FILE_API_TIMESTAMP, $current_time);
- // update $last_call for later use
- $last_call = $current_time;
- // - save the new data
- file_put_contents(FILE_API_DATA, $api_data);
- }
- }
- // check if we have new data, if not bring old data
- if (!$api_data) {
- if (file_exists(FILE_API_DATA))
- $api_data = file_get_contents(FILE_API_DATA);
- else
- $api_data = "no_data";
- }
- // finally, give the user the updated data:
- echo "Data updated at: ".date("d-m-Y H:i:s", $last_call);
- echo "<hr/>";
- echo $api_data;
Advertisement
Add Comment
Please, Sign In to add comment
Advertisement