I have nothing to do today and want to show the number of people online in the blog statistics. I found many examples on the Internet, either databases store data or files, and the code seems too complicated.
After I came back in the evening, I thought about it and saw that the Memcache service was installed on my server. Why not use Memcache to implement it.
Let’s talk about the implementation process:
Rendering:
Implementation code:
<?php $mc = new Memcache (); // 连接memcache $mc->connect ( "127.0.0.1", 11211 ); // 获取 在线用户 IP 和 在线时间数据 $online_members = $mc->get ( 'online_members' ); // 如果为空,初始化数据 if (! $online_members) { $online_members = array (); } // 获取用户ip $ip = $_SERVER ["REMOTE_ADDR"]; // 为访问用户重新设置在线时间 $online_members [$ip] = time (); foreach ($online_members as $k => $v) { // 如果三分钟后再未访问页面,刚视为过期 if (time() - $v > 180) { unset($online_members[$k]); } } // 重新设置在线用户数据 $mc->set ( 'online_members', $online_members ); // 重新获取在线用户数据 $online_members = $mc->get ( 'online_members' ); // 输入统计在线人数 echo count($online_members); ?>