Created
January 26, 2020 11:06
-
-
Save andrew-wilkes/08d72e32786018c5870e2aa2e7aee205 to your computer and use it in GitHub Desktop.
Unique Website Visitor Logger
This file contains hidden or bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
| <?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); | |
| } |
Author
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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.