Last active
December 17, 2015 10:49
-
-
Save c93614/5597963 to your computer and use it in GitHub Desktop.
A more easy way to count online users using php + apc/memcached or redis
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 | |
session_start(); | |
// ref: http://expressjs.com/guide.html#users-online | |
function get_online_user($session_id) { | |
if (false === ($online_users = apc_fetch("online/users"))) { | |
$online_users = []; | |
} | |
$online_users[$session_id] = time(); | |
$now = time(); | |
foreach($online_users as $session_id => $last_activity) { | |
if ($last_activity < $now - 60) { | |
unset($online_users[$session_id]); | |
} | |
} | |
apc_store("online/users", $online_users); | |
return array( | |
'count' => count($online_users), | |
'sessions' => array_keys($online_users), | |
); | |
} | |
var_dump(get_online_user(session_id())); |
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 | |
require 'predis/autoload.php'; | |
function get_online_user($session_id) { | |
$redis = new Predis\Client(); | |
$replies = $redis->pipeline(function($pipe) use($session_id) { | |
$key = 'online/sessions'; | |
$now = time(); | |
$pipe->zadd($key, $now, $session_id); | |
$pipe->zremrangebyscore($key, '-inf', $now - 300); // remove expired session | |
$pipe->zcard($key); | |
$pipe->zrevrange($key, 0, -1); | |
// $pipe->zrevrange('online/users', 0, -1, 'WITHSCORES'); | |
}); | |
return array( | |
'count' => $replies[2], | |
'sessions' => $replies[3], | |
); | |
} | |
session_start(); | |
echo "<pre>"; | |
print_r(get_online_user(session_id())); | |
echo "</pre>"; |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment
also read: