Last active
January 20, 2023 17:28
-
-
Save Fysac/10951082 to your computer and use it in GitHub Desktop.
Database-less, sessionless way to count online users in PHP.
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 | |
$timeout = 300; // 5 minutes | |
$time = time(); | |
$ip = $_SERVER["REMOTE_ADDR"]; | |
$file = "users.txt"; | |
$arr = file($file); | |
$users = 0; | |
for ($i = 0; $i < count($arr); $i++){ | |
if ($time - intval(substr($arr[$i], strpos($arr[$i], " ") + 4)) > $timeout){ | |
unset($arr[$i]); | |
$arr = array_values($arr); | |
file_put_contents($file, implode($arr)); // 'Glue' array elements into string | |
} | |
$users++; | |
} | |
echo $users; | |
// Only add entry if user isn't already there, otherwise just edit timestamp | |
for ($i = 0; $i < count($arr); $i++){ | |
if (substr($arr[$i], 0, strlen($ip)) == $ip){ | |
$arr[$i] = substr($arr[$i], 0, strlen($ip))." ".$time."\n"; | |
$arr = array_values($arr); | |
file_put_contents($file, implode($arr)); // 'Glue' array elements into string | |
exit; | |
} | |
} | |
file_put_contents($file, $ip." ".$time."\n", FILE_APPEND); | |
?> |
Hey @zubbey. It's been a while since I've done anything with this, but it should just work with any PHP runtime. All you need is a file called users.txt
in the same directory as this script. You probably want to set permissions on users.txt
to make sure people can't view it (it stores IP addresses, which could be sensitive).
Then when someone visits counter.php
, it will display how many unique IP addresses have also visited it in the last 5 minutes. You can integrate it with an existing website by including it as an iframe.
Thanks, man, it worked just fine.
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
Any Readme /Guide to implement this code to a project?