php 检测用户在线状态的实例代码
本文介绍下,
php 实现的检测用户在线状态的一段代码,有需要的朋友作个参考吧。
以下代码
ThinkPHP 框架,实现检测用户的在线状态。
1.先新建一个 tags.php 文件,放在配置目录 Conf 下。
<?php
/*
* 添加行为
*
*/
return array(
'action_begin' => array('OnlineCheck'),
);
?>
定义具体的功能
<?php
/*
* 定义行为: 在线更新
*/
class OnlineCheckBehavior extends Behavior {
//行为参数
protected $options = array(
'ONLINE_CHECK' => true, // 默认进行在线
'ONLINE_CHECK_TIME' => 10, // 默认 5 分钟未活动,说明已下线
);
public function run(&$params) {
if (C('ONLINE_CHECK')) {
// 更新 session
if ((session('?login_account')) && (time() - session('access_time') > 60)) {
session('access_time', time());
}
// 在线更新
$ip = ip2long(get_client_ip());
$online = M('Online');
//
先删除在线表中 超过
5 分钟未活动的记录
//$sql = ' delete from __TABLE__ where ';
$map['lasttime'] = array('lt', time() - C('ONLINE_CHECK_TIME') * 60);
$icount = $online->where($map)->delete();
if (session('?login_account')) { // 如果是登录用户
$map = array();
$map['uid'] = session('login_uid');
$map['lastip'] = $ip;
$id = $online->where($map)->getField('id');
if (empty($id)) { // 不存在在线记录,则清空 session