Last active
March 18, 2022 01:42
-
-
Save mbaersch/d7b7300958b7978b00642de52b006b15 to your computer and use it in GitHub Desktop.
Local caching helper for GTM containers
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
<?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