Skip to content

Instantly share code, notes, and snippets.

@mbaersch
Last active Mar 18, 2022
Embed
What would you like to do?
Local caching helper for GTM containers
<?php
/******************************************************************
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
//document.cookie='dbglive=1'
//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';".
"s.src='https://www.googletagmanager.com/gtm.js?id=$gtm_id';".
"document.getElementsByTagName('head')[0].appendChild(s);\n} else {\n";
$ch = curl_init("https://www.googletagmanager.com/gtm.js?id=$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);
curl_exec($ch);
curl_close($ch);
fwrite($fp,"\n}");
echo "cache updated";
} catch (Exception $ex) {
echo $ex->getMessage();
} finally {
fclose($fp);
}
?>
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment