How to cache a server call and check the cache expiration time before calling new data?

I use this script to get a list of Google web fonts. How can I cache the results and use them to determine whether to load from the cache or server call?

$googleFontsArray = array();
$googleFontsArrayContents = file_get_contents('http://phat-reaction.com/googlefonts.php?format=php');
$googleFontsArrayContentsArr = unserialize($googleFontsArrayContents);

foreach($googleFontsArrayContentsArr as $font)
{
    $googleFontsArray[$font['font-name']] = $font['font-name'];
}
0
source share
2 answers

You can make a local copy of serialized data and only update the file every hour:

$cache_file = 'font_cache';

$update_cache = false;
$source = $cache_file;
if(!file_exists($cache_file) || time() - filemtime($cache_file) >= 3600) // Cache for an hour
{
     $source = 'http://phat-reaction.com/googlefonts.php?format=php';
     $update_cache = true;
}

$googleFontsArray = array();
$googleFontsArrayContents = file_get_contents($source);
$googleFontsArrayContentsArr = unserialize($googleFontsArrayContents);

foreach($googleFontsArrayContentsArr as $font)
{
    $googleFontsArray[$font['font-name']] = $font['font-name'];
}

if($update_cache)
{
    file_put_contents($cache_file, $googleFontsArrayContents);
}
+2
source

, , - google. script. script, , , , .

0

All Articles