Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to create a tracking script with js and php?

Tags:

javascript

php

I want to create a simple tracking script to give to my clients. Something similar with GA but very basic.

The requirements are

  • give the clients a single and simple js script like google Analytics does
  • make most of the logic inside the js file loaded by 3th party sites from the main site
  • collect in PHP the information and store it

    What I can't figure yet is what are the ways to do this? Google from what I see is loading a gif file, stores the information and parses the logs. If I do something similar sending the data to a php file Ajax cross site policy will stop me, from what I remember.

    So what is a clean way to do this ? ( I don't need code just the logic behind it )

  • like image 493
    johnlemon Avatar asked May 10 '11 11:05

    johnlemon


    1 Answers

    Method a - web bug:

    Give the user this:
    <img src="http://www.yourserver.com/yourtracking.php?associateid=3rdpartyid" width="1" height="1" />

    have the php return header("content-type:image/gif"); and serve them a gif file for their effort.

    Method b - script

    Create a php file that can parse parameters and have it return content-type:text/javascript Have them load it like this: <script type="text/javascript" src="http://www.yourserver.com/yourtracking.php?associateid=3rdpartyid"></script>

    If you want to you can do additional stuff like

    <script type="text/javascript">
      var associateId = "12345";
      var trackingPage="homepage";
    </script>
    <script type="text/javascript" src="http://www.yourserver.com/yourtracking.php?associateid=3rdpartyid"></script>
    

    then in the php have code like this (watch the nested quotes)

    $str = 'var url = "http://www.yourserver.com/moretracking.php?associateid="+associateId+';
    $str .= '"&page="+trackingPage+"&ref="+escape(document.referrer);\n';
    $str .= 'document.write(\'<img src="\'+url+\'"/>\');';
    
    echo $str;
    
    like image 88
    mplungjan Avatar answered Oct 04 '22 13:10

    mplungjan