On my website, there is a possibility to download pdfs. Until here, everything is fine.
Now, I would like to track the pdf downloads. This can be done by using Google Analytics Events in the link of the pdf:
<a onclick="var that=this;_gaq.push(['_trackEvent','Download','PDF',this.href]);setTimeout(function(){location.href=that.href;},400);return false;" href="pdfs/my-file.pdf">Download my file</a>
The problem is that if somebady will download the pdf from a search engine, not directly from the website, this will not be tracked.
Do you know a proper method on how to track that?
Should I implement something on the server side when I am rendering the pdf, that will trigger a GA event?
Thank you in advance.
Here is one solution I just found:
php-ga Google Analytics for PHP
With php-ga, there is a possibility to simulate pageviews on the server side. So, now for me, when somebody downloads a pdf, I am also calling this code:
// Initilize GA Tracker
$tracker = new GoogleAnalytics\Tracker('UA-5824718-6', 'mdpi.com');
// Assemble Visitor information
// (could also get unserialized from database)
$visitor = new GoogleAnalytics\Visitor();
$visitor->setIpAddress($_SERVER['REMOTE_ADDR']);
$visitor->setUserAgent($_SERVER['HTTP_USER_AGENT']);
$visitor->setScreenResolution('1024x768');
// Assemble Session information
// (could also get unserialized from PHP session)
$session = new GoogleAnalytics\Session();
// Get filename from the previous request
$filename = parse_url(urldecode($_SERVER['REQUEST_URI']), PHP_URL_PATH);
// Assemble Page information
$page = new GoogleAnalytics\Page($filename);
$page->setTitle($filename);
// Track page view
$tracker->trackPageview($page, $session, $visitor);
$this->downloadFile($file, 'application/pdf');
The only problem I will have to fix is how to filter bots (Robots)...