Hi all,

I have been on this now for two weeks. Very much a neewbie.

Despite following Googles own instructions to the letter I just can't get the analytics cookie working on the following page:

<?php 
	
	$filename = {name};
	$filesize = filesize($filename); 
    $filetype = substr($filename, -3, 3); 

    switch($filetype) {   
        case "pdf": $mime="application/pdf"; break; 
        case "zip": $mime="application/zip"; break; 
        case "doc": $mime="application/msword"; break; 
        case "xls": $mime="application/vnd.ms-excel"; break; 
        case "ppt": $mime="application/vnd.ms-powerpoint"; break; 
        case "gif": $mime="image/gif"; break; 
        case "png": $mime="image/png"; break; 
        case "jpg": $mime="image/jpg"; break; 
        case "mp3": $mime="audio/mpeg"; break; 
        case "wav": $mime="audio/x-wav"; break; 
        case "mpg": 
        case "mpe": $mime="video/mpeg"; break; 
        case "mov": $mime="video/quicktime"; break; 
        case "avi": $mime="video/x-msvideo"; break; 

        default : $mime="application/octet-stream"; break; 
    } 

    header("Pragma: public"); 
    header("Expires: 0"); 
    header("Cache-Control: must-revalidate, post-check=0, pre-check=0"); 
    header("Cache-Control: public"); 
    header("Content-Description: File Transfer"); 
    header("Content-Transfer-Encoding: binary"); 

    header("Content-Type: {$mime}"); 
    header("Content-Length: {$filesize}"); 
    header("Content-Disposition: attachment; filename=\"{$filename}\";"); 
     
    @readfile($filename); 

?>

<br /> 
<script type="text/javascript">

  var _gaq = _gaq || [];
  _gaq.push(['_setAccount', 'UA-1511577-4']);
  _gaq.push(['_trackPageview']);

  (function() {
    var ga = document.createElement('script'); ga.type = 'text/javascript'; ga.async = true;
    ga.src = ('https:' == document.location.protocol ? '' : '') + '.google-analytics.com/ga.js';
    var s = document.getElementsByTagName('script')[0]; s.parentNode.insertBefore(ga, s);
  })();

</script>
<html>
<?php include ("header.php"); ?>
<body>
<?php include ("analyticsTracking.php"); ?>
</body>
</html>

Dani AI

Generated

Short diagnosis: the GA JavaScript in the download response will never reliably run because the server sends the file as an attachment (Content-Disposition: attachment) and the browser opens a download dialog instead of rendering the response HTML. That is why the analytics cookie never gets set by the snippet placed after the file is emitted. (mdn2.netlify.app)

Practical approaches (expand on ): if the download link is on a web page, track it on the link (onclick / gtag event) before navigating. If the link is sent in email (as and noted), client-side JavaScript inside the message will not run, so the usual onclick trick is not possible — most mail clients strip or block scripts. A safe pattern for emailed links is to point the link to a tiny intermediary tracking page (a short URL) that loads analytics, fires a pageview or event, then redirects to the actual download URL; GA4’s Enhanced Measurement will also auto-register clicks for common file types when enabled on the web stream. (help.brevo.com)

Server-side (robust) option: send an analytics hit from the server when the download script runs using Google Analytics’ Measurement Protocol (GA4). That avoids relying on client JS or redirect delays. Example (PHP, GA4 MP endpoint) — run this before serving the file:

<?php
$measurementId = 'G-XXXXXXX';
$apiSecret = 'API_SECRET';
$clientId = '555.1234567890'; // best if read from the _ga cookie when available

$payload = [
  'client_id' => $clientId,
  'events' => [
    ['name' => 'file_download', 'params' => ['file_name' => basename($filename)]]
  ]
];

$ch = curl_init("https://www.google-analytics.com/mp/collect?measurement_id={$measurementId}&api_secret={$apiSecret}");
curl_setopt($ch, CURLOPT_POST, true);
curl_setopt($ch, CURLOPT_HTTPHEADER, ['Content-Type: application/json']);
curl_setopt($ch, CURLOPT_POSTFIELDS, json_encode($payload));
curl_setopt($ch, CURLOPT_RETURNTRANSFER, true);
curl_exec($ch);
curl_close($ch);
// then emit headers + readfile(...)

See the GA4 Measurement Protocol docs for required parameters, quotas, and validation. (developers.google.com)

Notes and tradeoffs: the redirect landing-page approach preserves the normal client-side cookie/session and is simplest when links come from email; the Measurement Protocol approach is immediate and reliable for server-side counting but may not stitch into the same GA session unless the client_id (the _ga cookie) is captured and forwarded. When using client-side redirects, prefer gtag with an event_callback (or navigator.sendBeacon) so the hit is sent before navigating away. Test in GA’s Debug / Realtime to confirm. (developers.google.com)

Summary recommendation: for emailed download links use a short tracking page (load GA, then redirect) or implement server-side Measurement Protocol in the download script — either will record the click; pick the one that best preserves session continuity for reporting.

Recommended Answers

All 7 Replies

If this code is for downloading a file, it would be easier to put the tracking on the link that triggers this download.

Thanks for your suggestion Pritaeas -

Apologies fro being dumb but I'm a little confused by your suggestion: "put the tracking on the link that triggers this download". This page itself is the link that triggers the download.

just to clarify, this page is automatically generated when the client uploads the current file and is automatically named after the file: i.e. "currentfile.MP3.php". When the user clicks this link no page is displayed just the download file dialogue pops up. This has been designed so that users do not need to have the MP3 automatically play in their media player.

So what file is "the link that triggers the download" - or have I missed your point.

You say "When the user clicks this link". That is where you should add the tracking code.

Ah - I see - that's great - the only thing is that the link is sent via an email. Will this code be ok in an email?

Hmz, good question, probably not. Perhaps you could point them to a page that includes the tracking, and then redirect to the download script.

Perhaps this can work for you:

Thanks again Pritaeas, just got back - your advice looks useful - now in the process of checking

Interesting tidbit about google analytics. I noticed that google has keyword tool called school that lets you see others competitive keyword terms, but this only seems to show these keywords if you are using the google analytics. So, its something to consider when you decide to implement the free analytics code.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.