Home > Backend Development > PHP Tutorial > Website online people counting code implemented by php+memcache_PHP tutorial

Website online people counting code implemented by php+memcache_PHP tutorial

WBOY
Release: 2016-07-13 10:26:33
Original
728 people have browsed it

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:

<&#63;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);
&#63;>

Copy after login

www.bkjia.comtruehttp: //www.bkjia.com/PHPjc/824648.htmlTechArticleI 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. Back in the evening...
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template