Created
May 4, 2011 19:48
-
-
Save diogok/955879 to your computer and use it in GitHub Desktop.
Online Users using PHP and Redis
This file contains 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 | |
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 ; | |
} | |
} | |
?> |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
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 ;)