Timothy Bassett
Timothy Bassett

Reputation: 129

Google Analytics information in PHP

As I receive emails and leads from users on my site, I would like to tell who referred that particular user (ie: Organic, CPC, direct etc). While Google Analytics does this very well for weekly or even daily reporting, I would like to see that information for each enquiry or lead generated.

Is there anyway (in PHP) to access the Google Analytics data to determine a users source and/or medium?

Cheers,

Upvotes: 0

Views: 361

Answers (1)

Eike Pierstorff
Eike Pierstorff

Reputation: 32780

With ga.js you can do this quite easily by reading the google cookie. See the function below (not mine originally but I cannot give proper credit - I forgot where that came from). Note that this does not handle auto-tagged cpc visits, since those do not have utm parameters but a gclid url parameter (google click id).

With Universal Analytics, no. UA has a get method to retrieve the tracked values, but I didn't manage to retrieve the page source information beyond the visitors first page call, presumably because that information is no longer stored client side. You'd have to catch it when the visitors enter your site, write it to your own cookie and read that on the confirmation pages.

/*
* utmccn => campaign name
* utmcsr => campaign source
* utmcmd => campaign medium
* utmctr => campaign term or keyword
* utmcct => campaign content
*/
function GetAdwordsData_getUtm(){
                if(empty($_COOKIE['__utmz'])){
                               return false;
                }

                $utm = array();
                if(!empty($_COOKIE['__utmz'])){
                               $pattern = "/(utmcsr=([^\|]*)[\|]?)|(utmccn=([^\|]*)[\|]?)|(utmcmd=([^\|]*)[\|]?)|(utmctr=([^\|]*)[\|]?)|(utmcct=([^\|]*)[\|]?)/i";
                               preg_match_all($pattern, $_COOKIE['__utmz'], $matches);
                               if(!empty($matches[0])){
                                               foreach($matches[0] as $match){
                                                               $pair = null;
                                                               $match = trim($match, "|");
                                                               list($k, $v) = explode("=", $match);
                                                               $utm[$k] = $v;
                                               }
                               }
                } 

                return $utm;
}

Upvotes: 1

Related Questions