A Not So $h!tty Google-Analytics JavaScript Code

Posted at

icompile.eladkarako.com__a_not_so_htty_google_analytics_javascript_code

There are some new stuff running at Google,
making Analytics better then ever,
however, the javascript code raised a lot of eyebrows due to its complexity,

oh and the help-page for the user-visitors contains some UTF-8 weird stuff added by mistake to the code..

here is a "not so $h!tty stuff" that will not @#$ up your page, its broken down to 3 <script>
tags, that should be placed in the very end of the document, just before the closing body tag (</body>).

as a bonus there is an example on how to use the unique user-id featured (essentially everything new is here you can use the Analytics)

first, locate this in your very top of the page, just before the doctype area


<?php
  session_start();
  if(! isset($_SESSION['uniqueID'])){
    $_SESSION['uniqueID'] = uniqid();
  }

  setlocale(LC_ALL, 'he_IL.UTF-8');
  mb_internal_encoding('UTF-8');
  //setlocale(LC_CTYPE, 'en_US.UTF-8');
  //header('Content-Type: text/plain; charset=UTF-8'); //header('Content-Type: text/plain; charset=windows-1255');
?>
<!DOCTYPE html>
<html lang="en-US">
<head>


and this, at the end of the document



<script>
window["GoogleAnalyticsObject"] = "ga";
window["ga"] = window["ga"] || function(){
window["ga"].l = 1 * new Date();

window["ga"].q = window["ga"].q || [];
window["ga"].q.push(arguments);
};
</script>
<script src="https://www.google-analytics.com/analytics.js"></script>
<script>
window["ga"]("create", "UA-THE_CODE_FROM_GOOGLE-1", "THE_DETAIL_FROM_GOOGLE");
window["ga"]("require", "displayfeatures");
window["ga"]("require", "linkid", "linkid.js");
window["ga"]("set", "&uid", "<?php print($_SESSION['uniqueID']); ?>");
window["ga"]("send", "pageview");
</script>

</body>
</html>


extract your values ("UA-THE_CODE_FROM_GOOGLE-1" and "THE_DETAIL_FROM_GOOGLE") from your original Google-Analytics code-snippet,
your visitors will have an additional cookie, maintaining their identity on your website, this is 100% maintained by PHP, you can also use any PHP variable such as wordpress login name, or even a variation of the guest IP or any other detail you would like to track, and put it instead of the session-id, but, this is the easiest way.

note:
while processing the code I've came across some weird UTF-8 characters that were breaking my page,
this was due to I was copying&pasting it from Google-support, into my page,
solution was using Notepad++ to convert the PHP file to UTF-8, then the symbols were visible, and I've just deleted them, saved and uploaded the PHP file as binary through FTP.