Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How to track with Google Analytics on a redirection page with PHP?

Tags:

I have a website where I want to track who has clicked on specific links with GA.

Let's say I have this page: /index.php?id=32

On this page I run some query based on the ID variable (in this case: 32), and I get the URL of the 32 id item from the Database to redirect the visitor.

I'm using a PHP function: header('Location: http://www.example.com');. Before I'm redirecting the user, I want Google to capture the visitor's information and only then redirect to the desired webpage.

I have tried to paste the GA code and ECHO it just before the redirection, however it did not work. How is it possible to track these kind of pages with GA?

like image 382
Radical_Activity Avatar asked Dec 12 '14 23:12

Radical_Activity


People also ask

How a page is redirected in PHP?

The header function in PHP can be used to redirect the user from one page to another. It is an in-built function that sends raw HTTP header to the destination (client).


1 Answers

Generally speaking

If your page uses redirects, the redirecting page becomes the landing page's referrer. For example, if you've changed your site so that index.html now redirects to home.html, then index.html becomes the referrer for home.html. If someone reached your site via a Google search that sent them first to index.html, you won't have any data regarding the Google search.

For this reason, you should place the Google Analytics tracking code on the redirecting page as well as on the landing page. This way, the redirecting page will capture the actual referrer information for your reports.

Note, some browsers may actually redirect before the JavaScript call from the code can be made.

(cf. https://support.google.com/analytics/answer/1009614?hl=en)

Your specific case

Since PHP is rendered and executed before any Javascript, Google Analytics tracker has no chance to send data to its server.


Solutions

Considering that you cannot track a PHP redirection page, there are a number of possible alternatives:

  • Javascript redirection: https://stackoverflow.com/a/4745622/1672895
    • window.location = "http://www.yoururl.com";

  • Meta Refresh: https://stackoverflow.com/a/8692559/1672895
    • <meta http-equiv="refresh" content="5; url=http://example.com/">

  • Virtual page tracking: https://developers.google.com/analytics/devguides/collection/analyticsjs/pages
    • ga('send', 'pageview', '/index.php?id=32');

  • Campaign tracking (I wouldn't personally use this method in this specific case.)
    • /products.php?utm_source=index&utm_medium=redirection-page&utm_campaign=32

The last two items in the list are implemented on the individual links on the initial page before you get on the PHP redirection page.

like image 198
carlodurso Avatar answered Sep 20 '22 06:09

carlodurso