Google 分析实际上有一个用于从任意来源发送分析数据的协议。见这里:https://developers.google.com/analytics/devguides/collection/protocol/v1/
因此,让您的网络服务器向 Google 发送分析事件并不像看起来那么难。我不确定您是否可以直接连接到 Apache 以生成这些事件。不过,我确实看到了至少两种解决方案。
1) 将所有下载重定向到服务器端脚本,该脚本发送数据并可以生成所需的分析事件。
2) 解析服务器日志并从中生成分析事件。
解决方案 1 的编辑示例:
请确保标签前后没有空格,因为这将是发送给客户端的实际响应的一部分。
下载.php:
<?php
// Read ?file=xxx URL parameter
$requestedFile = $_GET["file"];
// Read Google Analytics cookie
$rawCookie = $_COOKIE["_ga"];
$splitCookie = explode('.', $rawCookie);
$trackingId = $splitCookie[2] . '.' . $splitCookie[3];
// Create Google Analytics request data (see here https://developers.google.com/analytics/devguides/collection/protocol/v1/devguide)
$data = array('v' => 1,
'tid' => 'UA-XXXXX-Y',
'cid' => $trackingId,
't' => 'event',
'ec' => 'download',
'ea' => 'download',
'el' => $requestedFile);
// Create the request options
$options = array(
'http' => array(
'method' => 'POST',
'content' => http_build_query($data)
)
);
$context = stream_context_create($options);
// Send GA request
$result = file_get_contents('https://www.google-analytics.com/collect', false, $context);
// GA request failed
if($result === FALSE) { /* Error */ }
// Requested file does not exist
if(!file_exists($requestedFile)) { /* Error */ }
// Set response headers for binary data
header('Content-Type: application/octet-stream');
header('Content-Length: ' . filesize($requestedFile));
// Open the requested file
$fileHandle = fopen($requestedFile, 'r');
// Write the requested file to stdout (which is what the client receives)
print fread($fileHandle, filesize($requestedFile));
flush();
// Close the requested file again
fclose($fileHandle);
exit;
?>
.htaccess/mod_rewrite 规则:
RewriteEngine on
RewriteUrl ^/download/(.*)$ download.php?file=$1 [L]
自从我编写最后一个 PHP 代码并且我没有对此进行测试已经过去了很多年。但它应该为如何实现选项 1) 提供一个很好的要点)
编辑 2:如果您将跟踪请求发送到 www.google-analytics.com/debug/collect,您将收到一些验证信息,告诉您您的请求是否有效(但它不会跟踪事件)。
编辑 3:
好的,所以我检查了一个使用 analytics.js 的页面。该脚本设置以下 cookie:
_ga=GA1.3.1788966449.1501761573
_gid=GA1.3.1010429060.1501761573
稍后在它设置的收集请求中
cid:1788966449.1501761573
_gid:1010429060.1501761573
因此,您似乎需要对 _ga cookie 中的内容进行一些字符串拆分。 (我已经更新了上面的代码)
编辑 4:如果有人想知道,这是 analytics.js 脚本使用上述 cookie 值生成的请求。
GET https://www.google-analytics.com/collect?v=1&_v=j56&a=1178408574&t=pageview&_s=1&dl=https%3A%2F%2Fdevelopers.google.com%2Fanalytics%2Fdevguides%2Fcollection%2Fanalyticsjs%2Fcommand-queue-reference&ul=de&de=UTF-8&dt=The%20ga%20Command%20Queue%20Reference%20%C2%A0%7C%C2%A0%20Analytics%20for%20Web%20(analytics.js)%20%C2%A0%7C%C2%A0%20Google%20Developers&sd=24-bit&sr=1920x1200&vp=1899x1072&je=0&_u=QDCAAAIhI~&jid=&gjid=&cid=1788966449.1501761573&tid=UA-41425441-2&_gid=1010429060.1501761573&z=1116872044