Skip to content

Instantly share code, notes, and snippets.

Last active March 18, 2022 01:42
What would you like to do?
Local caching helper for GTM containers
Helper for locally cached GTM container: update local GTM cache and
enable optional live container loading for debugging
//path and filename for local GTM container cache, relative
//to this PHP file or as absolute server path
$gtm_save_path = "../js/gtm.js";
//ID for GTM container to be cached in local file specified above
$gtm_id = "GTM-XYZABC";
//NOTE: better use a .htaccess secured file for this or somethin similar.
//As an example for minimum security you _could_ use a constant key as
//GET parameter - which is definitely not the best way to secure this
//helper that downloads an external file and places it on your server!
if ($_GET['secretkey'] !== 'mysecretpassword') die('go away!');
//load container JS and store locally and enable live container
//loading for debugging. To use live container, just type
//in your browser`s console
try {
$fp = fopen($gtm_save_path, 'wb');
$ld = "\nif (document.cookie.indexOf('dbglive=1') >= 0) {".
"\nvar s=document.createElement('script');s.type='text/javascript';".
"document.getElementsByTagName('head')[0].appendChild(s);\n} else {\n";
$ch = curl_init("$gtm_id");
$fp = fopen($gtm_save_path, 'wb');
fwrite($fp,"//**Cached GTM** last update:".date("Y-m-d H:i:s").$ld);
curl_setopt($ch, CURLOPT_FILE, $fp);
curl_setopt($ch, CURLOPT_HEADER, 0);
echo "cache updated";
} catch (Exception $ex) {
echo $ex->getMessage();
} finally {
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment