Skip to content

Instantly share code, notes, and snippets.

@jamesBan
Forked from diogok/OnlineUsers.php
Last active August 29, 2015 14:24
Show Gist options
  • Save jamesBan/845d0ce15813752e3b56 to your computer and use it in GitHub Desktop.
Save jamesBan/845d0ce15813752e3b56 to your computer and use it in GitHub Desktop.
<?php
//http://flask.pocoo.org/snippets/71/ that is good idea
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