Ștefan-Costin Ilinca
Ștefan-Costin Ilinca

Reputation: 23

Updating php script one time per day

I am making a Covid-19 statistics website - https://e-server24.eu/ . Every time somebody is entering the website, the PHP script is decoding JSON from 3 urls and storing data into some variables. I want to make my website more optimized so my question is: Is there any script that can update the variables data one time per day, not every time someone accesses the website?

Thanks,

Upvotes: 2

Views: 201

Answers (2)

wp78de
wp78de

Reputation: 18950

I suggest looking into memory object caching.

Many high-performance PHP web apps use caching extensions (e.g. Memcached, APCu, WinCache), accelerators (e.g. APC, varnish) and caching DBs like Redis. The setup can be a bit involved but you can get started with a simple role-your-own solution (inspired by this):

<?php
function cache_set($key, $val) {
   $val = var_export($val, true);
   // HHVM fails at __set_state, so just use object cast for now
   $val = str_replace('stdClass::__set_state', '(object)', $val);
   // Write to temp file first to ensure atomicity
   $tmp = sys_get_temp_dir()."/$key." . uniqid('', true) . '.tmp';
   file_put_contents($tmp, '<?php $val = ' . $val . ';', LOCK_EX);
   rename($tmp, sys_get_temp_dir()."/$key");
}

function cache_get($key) {
    //echo  sys_get_temp_dir()."/$key";
    @include sys_get_temp_dir()."/$key";
    return isset($val) ? $val : false;
}

$ttl_hours = 24;
$now = new DateTime();

// Get results from cache if possible. Otherwise, retrieve it.
$data = cache_get('my_key');
$last_change = cache_get('my_key_last_mod');
if ($data === false || $last_change === false || $now->diff($last_change)->h >= $ttl_hours ) { // cached? h: Number of hours.
    // expensive call to get the actual data; we simple create an object to demonstrate the concept
    $myObj = new stdClass();
    $myObj->name = "John";
    $myObj->age = 30;
    $myObj->city = "New York";    
    $data = json_encode($myObj);
    // Add to user cache 
    cache_set('my_key', $data);

    $last_change = new DateTime(); //now
    // Add timestamp to user cache
    cache_set('my_key_last_mod', $last_change);
}

echo $data;

Voila.

Furthermore; you could look into client-side caching and many other things. But this should give you an idea.

PS: Most memory cache systems allow to define a time-to-live (TTL) which makes this more concise. But I wanted to keep this example dependency-free. Cache cleaning was omitted here. Simply delete the temp file.

Upvotes: 2

Tinesh Nehete
Tinesh Nehete

Reputation: 31

Simple way to do that Create a script which will fetch , decode JSON data and store it to your database. Then set a Cron jobs with time laps of 24 hours . And when user visit your site fetch the data from your database instead of your api provider.

Upvotes: 2

Related Questions