Skip to content

Instantly share code, notes, and snippets.

Embed
What would you like to do?
Online Users using PHP and Redis
<?php
include 'predis/predis.phar';
class OnlineUsers {
/* time to consider user online */
private $minutes = 5 ;
function online() {
/* current hour and minute */
$now = time();
$min = date("i",$now);
$hor = date("G",$now);
/* redis keys to union, based on last $minutes */
$keys = array();
for($i = $min ; $i >= $min - $this->minutes; $i--) {
$keys[] = "online:".$hor.":".$i; // define the key
}
$redis = new Predis\Client(); // connect to redis at localhost
$scmd = $redis->createCommand("sunion",$keys); // create the union with desired keys
$online = $redis->executeCommand($scmd); // issue the sunion and grab the result
return $online ; // array of online usernames
}
function ping($user) {
/* current hour:minute to make up the redis key */
$now = time();
$min = date("G:i",$now);
$key = "online:".$min;
$redis = new Predis\Client(); // connect to redis at localhost
$redis->sadd($key,$user); // add the user to the set
$ttl = $redis->ttl($key) ; // check if key has an expire
if($ttl == -1) { // if it do not have, set it to $minutes + 1
$redis->expire($key, ($minutes + 1) * 60);
}
return $this ;
}
}
?>
@NodexTech
Copy link

Just an FYI but your online() function is won't work when it comes to counting to the previous hour - i/e 12:01, 12:00, 11:59..... it's better to add the elapsed minutes since midnight $elapsed=floor((time() - strtotime("today")) /60); and adding that as the online: key - this still breaks overnight to the last day but that's edge cases.

I will come up with a better implementation that crosses over to yesterday too and update here ;)

@sreenadh
Copy link

sreenadh commented Apr 5, 2015

@NodexTech +1.
Use "expireat" .

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