Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
<?php
$landing = '/';
$goal = '/metric?signup';
$retention = '/metric?signin';
$dir = __DIR__ . '/nginx';
$full = __DIR__ . '/full.log';
unlink($full);
for($i=0;$i<100;$i++) {
$append = ($i) ? '.' . $i : '';
$filename = $dir . '/access.log' . $append;
if (!file_exists($filename)) break;
echo $filename . PHP_EOL;
system('cat ' . $filename . ' | grep -v 400 | grep -v 301 | grep -v 302 | grep GET >> ' . $full);
}
$log = array();
$fp = fopen($full, 'r');
while ($line = fgets($fp, 4000)) {
// 8.8.8.8 - - [01/Mar/2013:15:46:51 +0000] "GET /metric?facebook-page HTTP/1.1" 200 6533 "http://www.truesocialmetrics.com/connect/facebook-page" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10.5; rv:12.0) Gecko/20100101 Firefox/12.0"
preg_match('~^([0-9\.]+)\s+-\s+-\s+\[([^\]]+)\]\s+"([^"]+)"~', $line, $match);
//var_dump($match);
list($method, $uri, $protocol) = explode(' ', $match[3]);
$log[] = array(
'ip' => $match[1],
'time' => date('Ymd', strtotime($match[2])),
'uri' => $uri,
);
}
$log = array_reverse($log);
$ips = array();
foreach ($log as $item) {
$ip = $item['ip'];
if (!array_key_exists($ip, $ips)) {
$ips[$ip] = array(
'items' => array(),
'step' => 0,
'goal_at' => 0,
'retention_at' => 0,
);
}
$ips[$ip]['items'][] = $item;
}
// step goal calculation
$closure = function($value) use ($goal, $retention) {
$step = 0;
$time = 0;
$successGoal = false;
foreach ($value['items'] as $item) {
if ($item['uri']==$goal) {
$successGoal = true;
$time = $item['time'];
break;
}
$step++;
}
if ($successGoal) {
$value['step'] = $step;
$value['goal_at'] = $time;
}
return $value;
};
$ips = array_map($closure, $ips);
$ips = array_filter($ips, function($value){
return $value['step']>0;
});
echo 'step' . "\t" . 'unique visitors' . PHP_EOL;
$steps = array();
foreach ($ips as $value) {
$step = $value['step'];
if (!array_key_exists($step, $steps)) {
$steps[$step] = 0;
}
$steps[$step]++;
}
ksort($steps);
foreach ($steps as $step => $value) {
echo $step . "\t" . $value . PHP_EOL;
}
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment
You can’t perform that action at this time.