考虑两种情况:
(1)用户关闭浏览器或重定向到其他网页
<script type="text/javascript"> <BR>function exit_init() { <BR>if(xmlhttp.readyState==4){ <BR>if(xmlhttp.status==200){ // <BR>} <BR>else{ <BR>alert("there was a problem accessing the server:"+xmlhttp.status); <BR>} <BR>} <BR>} <BR>//定义windows 的onbeforeunload 事件,当用户非正常退出即浏览器非正常关闭时,对用户登录状态进行处理 <BR>window.onbeforeunload=function () { <BR>//if(event.clientY<0||event.altKey) { <BR>exit_request = false; <BR>//创建请求对象 <BR>if (window.XMLHttpRequest) { <BR>exit_request = new XMLHttpRequest(); <BR>if (exit_request.overrideMimeType){ <BR>exit_request.overrideMimeType('text/xml'); <BR>} <BR>} else if (window.ActiveXObject) { <BR>try{ <BR>exit_request = new ActiveXObject("Msxml2.XMLHTTP"); <BR>} catch (e) { <BR>try { <BR>exit_request = new ActiveXObject("Microsoft.XMLHTTP"); <BR>} catch (e) { <BR>} <BR>} <BR>} <BR>if (!exit_request) { <BR>alert("Your brower is not compatible the current opration.Please use the IE 5.0! "); <BR>return false; <BR>} <BR>var url='null.php?userid='+document.getElementById("userid").value; <BR>//定义页面调用的方法exit_init,不是exit_init();没有(); <BR>exit_request.onreadystatechange = exit_init; <BR>exit_request.open('GET', url, true); <BR>//禁止IE 缓存 <BR>exit_request.setRequestHeader("If-Modified-Since","0"); <BR>//发送数据 <BR>exit_request.send(null); <BR>} <BR>//} <BR></script>
说明:null.php用来将用户状态设为下线
(2)用户长时间不再浏览本网站
思路:创建表active_stat,属性有userid,lasttime,nowtime。用户每打开一次本网站,更改lasttime为当前时间now(),每隔1分钟更改nowtime为当前时间,判断nowtime-lasttime是否大于20分钟,若大于,则修改用户状态为下线
<script language="javascript"> <BR>function test(userid){ <BR>setInterval("offline('"+userid+"')", 60000 ); //每隔1分钟执行一次 <BR>} <BR>function offline(userid){ <BR>var xmlhttp=false; <BR>try{ <BR>xmlhttp=new activeXObject('Msxml2.XMLHTTP'); <BR>}catch(e){ <BR>try{ <BR>xmlhttp=new ActiveXObject('Microsoft.XMLHTTP'); <BR>}catch(e){ <BR>try{ <BR>xmlhttp=new XMLHttpRequest(); <BR>}catch(e){} <BR>} <BR>} <BR>if(xmlhttp.readyState==4||xmlhttp.readyState==0) <BR>{ <BR>xmlhttp.open('get','../user/include/offline.php?userid='+userid,false); <BR>xmlhttp.onreadystatechange=function(){ <BR>if(xmlhttp.readyState==4){ <BR>if(xmlhttp.status==200){ <BR>// <BR>} <BR>else{ alert("there was a problem accessing the server:"+xmlhttp.status);} <BR>} <BR>} <BR>xmlhttp.send(null); <BR>} <BR>} <BR></script>
offline.php
//连接数据库
$userid=$_GET["userid"];
pg_exec("update active_stat set nowtime=now() where userid='".$userid."';");
$result=pg_exec($dbconn,"select (nowtime-lasttime) as activetime from active_stat where userid='".$userid."'");
$str=pg_result($result,0,"activetime");
if(strlen($str)>16){
$array=explode(" ",$str);
$t=explode(":",$array[1]);
$t[0]=$t[0]+$array[0]*24;
$s=explode(".",$t[2]);
$t[2]=$s[0];
$y=((int)$t[0])*3600+((int)$t[1])*60+((int)$t[2]);
}
else{
$total_time=explode(".",$str);
$x=explode(":",$total_time[0]);
$y=((int)$x[0])*3600+((int)$x[1])*60+((int)$x[2]);
}
if($y>=1200){
pg_exec("update users set status='f' where userid='".$userid."';");
}
?>


















