Skip to content

Instantly share code, notes, and snippets.

@sponno
Created September 25, 2018 04:12
Show Gist options
  • Save sponno/ac64e62bf9f49b4b95a4123626a12820 to your computer and use it in GitHub Desktop.
Save sponno/ac64e62bf9f49b4b95a4123626a12820 to your computer and use it in GitHub Desktop.
<?php
/**
* This is simple caching function for PHP, that save the contents from a URL and store it on desk.
* It uses the file last modified date to figure out when to expire the cache.
* 1. Update the SCHEMA URL to your AskNicely Schema URL
* 2. You might want to update the cache file location, PHP will need write access to the cache location.
*/
function getAskNicelySchema($cacheHours = 4){
$schemaURL = "https://reviews.asknicely.site/reviews/test/schema"; // #1 PLEASE UPDATE TO THE CORRECT URL
$cacheFileName = __DIR__."/schema.json"; // #2 THIS WILL CACHE THE FILE IN THE SAME FOLDER AS YOU PHP SCRIPT.
if (!file_exists($cacheFileName) || (time() - filemtime($cacheFileName) > $cacheHours * 3600) /*4 hours by default*/
) {
$body = file_get_contents($schemaURL);
file_put_contents($cacheFileName, $body);
}
return "<script type='application/ld+json'>".file_get_contents($cacheFileName)."</script>"; // USE THIS CONTENT FOR YOUR HTML PAGE.
}
echo getAskNicelySchema();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment