Skip to content

Instantly share code, notes, and snippets.

@andrew-wilkes
Created January 26, 2020 11:06
Show Gist options
  • Select an option

  • Save andrew-wilkes/08d72e32786018c5870e2aa2e7aee205 to your computer and use it in GitHub Desktop.

Select an option

Save andrew-wilkes/08d72e32786018c5870e2aa2e7aee205 to your computer and use it in GitHub Desktop.
Unique Website Visitor Logger
<?php
const TESTING = false;
const FILE_NAME = ".hits";
const DAYS = 10;
const PASSWORD = "YOUR PASSWORD HERE";
$user_agent = strip_tags($_SERVER['HTTP_USER_AGENT']);
$bots = ["bot", "slurp", "spider", "crawler"];
foreach ($bots as $bot) {
if (stripos($user_agent, $bot) !== false) exit();
}
$today = date('j');
$log = "";
// Get the data
$data = [
'today' => $today,
'records' => []
];
if (is_file(FILE_NAME))
$data = (array) json_decode(file_get_contents(FILE_NAME));
else
for($n = 0; $n < DAYS; $n++)
$data['records'][] = [];
if (isset($_POST["x"]) && $_POST["x"] == PASSWORD)
exit(json_encode($data));
// Check for new day
if ($data['today'] != $today) {
$data['today'] = $today;
for($n = DAYS - 1; $n > 0 ; $n--)
$data['records'][$n] = $data['records'][$n - 1];
$data['records'][0] = [];
}
// Log hit
$ip = preg_replace('/[^.:0-9a-z]/', '', $_SERVER['REMOTE_ADDR']);
if (in_array($ip, $data['records'][0]))
$log = "Existing $ip";
else {
$data['records'][0][] = $ip;
$log = "Added $ip";
file_put_contents(FILE_NAME, json_encode($data));
}
if (TESTING) {
echo $log;
print_r($data);
}
@andrew-wilkes

Copy link
Copy Markdown
Author

The script creates an array of unique IPv4 addresses for each day. So the visitor count may be deduced from the array sizes. Also, there is a primitive web bot filter applied to try to eliminate web bots that may use JavaScript from the results.

My idea is to create an automated reporting tool that gathers this data from my sites and creates a daily report for me that is saved to my PC.

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment