Home  >  Article  >  Backend Development  >  How to determine if the user is online in php

How to determine if the user is online in php

(*-*)浩
(*-*)浩Original
2019-09-20 09:55:484365browse

There are many ways to determine whether a user is offline or online. Here is a relatively simple and commonly used logic.

How to determine if the user is online in php

Ideas:

1: First get the user’s last saved session_id (recommended Learning: PHP programming from entry to proficiency)

//这里可以保存到数据库中获取
//假设
$memberSessionId = getMemberSessionId();

2: Use the session_id obtained in the first step to find whether the current session exists

//只要开启了session_start() ; 那么每个用户只要打开你的网站都将分配一个session_id
/* 这段代码可以获取到你服务器上的所有session
$handle = opendir(session_save_path());
while (false !== ($file = readdir($handle))) {
if(!in_array($file, array('.', '..', 'session_dir')))
echo "$file<br />";
}
closedir($handle);
*/
//这一步要获取到你在服务器上和用户匹配的session
// 假设
$serverSession == $memberSessionId // 如果存在,则在线,否则反之

Three: If the user exits normally, delete the current session

// 将全局SESSION变量数组设置空.
$_SESSION = array();
// 如果SESSION数据存储在COOKIE中则删除COOKIE.
// Note: 将注销整个SESSION对象, 而不仅仅是SESSION数据!
if (isset($_COOKIE[session_name()])) {
setcookie(session_name(), &#39;&#39;, time()-42000, &#39;/&#39;);
}
// 最后,注销SEESION.
session_destroy();

Four, if the user closes the browser directly, wait for the server session to be recycled

The above is the detailed content of How to determine if the user is online in php. For more information, please follow other related articles on the PHP Chinese website!

Statement:
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