Skip to content

Instantly share code, notes, and snippets.

@Fysac
Last active January 20, 2023 17:28
Show Gist options
  • Star 5 You must be signed in to star a gist
  • Fork 3 You must be signed in to fork a gist
  • Save Fysac/10951082 to your computer and use it in GitHub Desktop.
Save Fysac/10951082 to your computer and use it in GitHub Desktop.
Database-less, sessionless way to count online users in PHP.
<?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);
?>
@zubbey
Copy link

zubbey commented Nov 16, 2019

Any Readme /Guide to implement this code to a project?

@Fysac
Copy link
Author

Fysac commented Nov 17, 2019

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.

@zubbey
Copy link

zubbey commented Nov 17, 2019

Thanks, man, it worked just fine.

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