Skip to content

Instantly share code, notes, and snippets.

@marcelweder
Last active September 14, 2016 06:25
Show Gist options
  • Star 1 You must be signed in to star a gist
  • Fork 0 You must be signed in to fork a gist
  • Save marcelweder/87d0be2b151abc9f52840440666eb420 to your computer and use it in GitHub Desktop.
Save marcelweder/87d0be2b151abc9f52840440666eb420 to your computer and use it in GitHub Desktop.
Workaround to implement Google-Analytics script
<?php
/**
* Google-Analytics
* Do not forget to replace te ID (UA-00000000-0)
*/
$alternate = '(function(root){
root.GoogleAnalyticsObject = "ga";
root.ga = {q: [["create", "UA-00000000-0", "auto"]],l: 1 * new Date()};
})(this);';
function get_url($url)
{
$ch = curl_init();
curl_setopt($ch, CURLOPT_URL, $url);
curl_setopt($ch, CURLOPT_HTTPHEADER, array(
'Content-type: application/javascript'
));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, 1);
curl_setopt($ch, CURLOPT_FRESH_CONNECT, 1);
curl_setopt($ch, CURLOPT_CONNECTTIMEOUT, 0);
curl_setopt($ch, CURLOPT_TIMEOUT, 5); //timeout in seconds
$content = curl_exec($ch);
curl_close($ch);
return $content;
}
function get_content($file, $url, $hours = 24, $fn = '', $fn_args = '')
{
$current_time = time();
$expire_time = $hours * 60 * 60;
$file_exists = file_exists($file);
if ($file_exists)
{
$file_time = filemtime($file);
}
if ($file_exists && ($current_time - $expire_time < $file_time))
{
$content = file_get_contents($file);
$content.= '/* cachedtype: js */';
}
else
{
$content = get_url($url);
if ($content && $fn)
{
$content = $fn($content, $fn_args);
}
if ($content)
{
$content.= '/* cachedtime: ' . time() . ' */';
file_put_contents($file, $content);
}
}
return $content;
}
function get_script($file, $url)
{
global $alternate;
$time = time();
$response = get_content($file, $url);
if ($response === false)
{
$response = $alternate;
}
$headers = array(
'Content-Type' => 'application/javascript',
'Last-Modified' => gmdate('D, d M Y H:i:s T', $time) ,
'Expires' => gmdate('D, d M Y H:i:s T', strtotime('+30 days', $time)) ,
'Cache-Control' => 'public',
);
header("HTTP/1.1 200 OK");
foreach ($headers as $key => $value)
{
header($key . ':' . $value);
}
echo $response;
}
get_script('ga.js', 'https://www.google-analytics.com/analytics.js');
die();
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment