How to attach Google Analytics code from your own server
This task can be accomplished in a very simple way using the PHP script. It's not the way Google proposes and the way I came across it on the Internet. Its advantage is that we have an influence on setting the expiry date of static resources in the HTTP header, maximum time and use of browser cache.
We create a PHP file called analytics.php And we'll add the code:
$context = stream_context_create(['http' => ['Content-Type' => 'text/javascript', 'enable_cache' => true, 'enable_optimistic_cache' => true, 'read_cache_expiry_seconds' => 604800,]]); echo file_get_contents("https://www.google-analytics.com/analytics.js", false, $context); Then we simply replace the address https://www.google-analytics.com/analytics.js with our analyticals.php file and ready.
I checked that way and it works. I haven't tested it for long, but I didn't see any abnormalities. However, remember that some irregularities may occur in longer use or specific circumstances. I personally just started using Piwik as an alternative.