Several ways to achieve statistical online users

Source: Internet
Author: User
Tags comments sessions
One, each user action updates its online time

This method is straightforward, add a field to the user table Update_time, each time the user is operated, update this field for the current time, typically in a base class that is inherited by all actions.

Then define an expiration time, such as 10 minutes, which means that the user who has not done anything for 10 minutes defaults to No line. So, the SQL statement that counts the current online user is probably this

Select COUNT (*) from Think_user where Update_time>now () -10*60

Advantages: Simple to implement, easy to understand the shortcomings: 1, the definition of "online" fuzzy, in case the user read an article time is longer, 10 minutes without any operation, he was ignored; 2, if the user table data is very large, that efficiency will be extremely

Poor

Second, put online users into a single table

For the improvement of method one. Create a new table Think_inline, the field has user_id, update_time, each user operation, the first judge whether there is a record of the user, no new, there will be updated update_time.
Plus delete invalid data operation

Delete from Think_inline where Update_time<now () -10*60 So, the statistics online can be directly count this table on the line. And the amount of data on this table is not very large (at least much smaller than the user's table).

Benefits: Reduce Database pressure

Disadvantage: The definition of "online" is still inaccurate

Third, with the JS timer

This method was integrated one and two. Create a new table Think_inline, also in the base class to define each user action update time, refer to the practice of two.

The difference is that in each HTML template, add a JS timer, setinterval (' UpdateTime ', 10*3600), send an AJAX request every 10 minutes, and update the Update_time field. This way, even if the user is on a page

The stay is too long and will not be mistaken for being online. and can increase the accuracy by reducing the interval of the request, of course, the pressure on the server is even greater.

Advantages: Accurate judgment on the line

Disadvantage: It is still not accurate and does not increase the pressure on the server, you must choose between the two.

Four, using TP's SESSIONDB drive to optimize the design

This is the internet, someone said the session into the database method, this method has many advantages.

1, why should the session be stored in the database.

A session is a set of temporary data stored on a server. In general, when we do user login, the user data will be stored in session. This makes it easy to invoke on any page, and each client produces a unique

session_id, do not mix the delicacies. And after the browser is closed, the server will have a session recycling mechanism to automatically delete expired sessions.

This is the advantage of the session: uniqueness, easy to invoke, does not consume too much resources. But there are drawbacks: cookies are not used when the client is saved as cookies.

So, how does the server store the session? He is the default to save the session as a file on the hard disk. However, for our code farmers, the operation of the database is more convenient than reading files, and can

Data for various operations.

and the number of online users is calculated by counting the number of session records to achieve.

2, how to save the session to the database.

The SESSIONDB drive of TP realizes this function. The principle is to rewrite the PHP default session operation to achieve, the core function Session_set_save_handler (), interested can be studied. The drive will

The session of the increase, read, take, and delete all into the database.

The use of the method is also very simple: 1, build the table, driving the comments in the SQL statements run under the good

2, add the configuration:

Session configuration ' Session_type ' => ' db ',//Database storage session ' session_table ' => ' Think_sessio n ',//Save session table ' Session_expire ' =>,//session expiration time in this way, as long as we use the sessions () function in the program, there will be records in the database.

3, using database session to realize statistics online users

1, total number of online statistics

$map = Array (' Session_expire ' =>array (' GT ', Now_time)); $inline = D (' session ')->where ($map)->count (); 2, statistics visitors (not logged in) number

$map = Array (' Session_expire ' =>array (' GT ', now_time), ' Session_data ' =>array (' eq ', ')); $huiyuan = D (' session ')->where ($map)->count (); 3, Statistics member (already logged in) number

$map = Array (' Session_expire ' =>array (' GT ', now_time), ' Session_data ' =>array (' neq ', ')); $huiyuan = D (' session ')->where ($map)->count (); 4, to determine whether a user online.

Add a field to the user table: session_id.

(1) In the login operation, save the user's session_id,

$session _id = session_id (); D (' User ')->where (array (' ID ' => $user _id))->save (' session_id ' => $session _id); (2) Check whether the session_id exists in the table, does not expire and has a value,

$map = Array (' session_id ' => $session _id, ' Session_expire ' =>array (' GT ', now_time), ' Session_data ' =>array ('         Neq ', ')); $res = D (' session ')->where ($map)->find (); if ($res) {dump (' This user is online. ')}else{dump (' The user is not on line. ')} 4, summary

1, the implementation step: User table new Field save session_id, using TP SESSIONDB drive. is not very simple.

2, Advantages:

(1) than the above three methods of database and server pressure is small, easy to operate

(2) can distinguish whether the online user is a member or a tourist (session_data field has a value), Discuz is to do so

(3) The function of "kicking off the line" can be realized by deleting a user's session record.

3, Disadvantages:

(1) Still not accurate statistics, can only say, xx seconds online how many people

4, Note:

(1) because the sessiondb driver of this method must use the session () function to trigger, you must configure the Auto open session (the default is open). TP uses the session () function in the execution process, so what do you

are not written, the session data is also stored in the database.

(2) because the database session data is not deleted by itself, so for outdated data, must call the sessions () method will be deleted.

This means that if your site is not accessed by one person, the expiration session record for the database will persist.

That is because of this mechanism, for some unexpected events (user direct X browser, direct shutdown, earthquake ...). , when the browser is closed for a period of time (session expiration), other users ' access to the Web site

Triggers a session recycle to delete an expired record. Therefore, not afraid of statistical data is inaccurate.

Of course, even if no one is visiting, you can also count by adding session_expire>time ().

But also has the error, is the session expiration time, after 5 minutes expires, has 5 minute error. The smaller the time, the more frequent the operation of the database, the greater the accuracy the lower.

(3) This session expiration means that if the user does not take any action within 5 minutes, it will automatically exit the login. So, for the user experience good, please add the cookie automatic login function. That's what the official website is for now.

Of

(4) It is mentioned in the comments that the verification code will also be stored in the session, so when we judge, we can not count the value of the record.
You need to first get the data that has value, and then judge if there is a parameter name that holds no user information. Although the Session_data field is stored in binary, the query is a string.
For example, we use user subscript to save information, session (' user ', $data)//user login information//Get real Membership number/query value of the session record $list = D (' session ')->where ( Array (' Session_data ' =>array (' neq ', '), ' Session_expire ' =>array (' lt ', Now_time))->select (); Determine whether there is a member of the identification foreach ($list as $k => $value) {if (Strpos ($value [' Session_data '], ' user ') = = False) {$cou             nt++; Dump ($count);//True number of members}

(5) Because each browser has its own session mechanism, so if a person on a computer at the same time open 5 kinds of browsers, the database will save 5 different records

In actual use, still need to consider the error of search engine. When it crawls our page, it also produces a session.

Five, final conclusion

Due to the limitation of the HTTP protocol: the connection to the client is disconnected when the request completes. So in fact,

We simply cannot count the number online in real time.

Although there are a variety of methods to increase the accuracy of statistics, but the symptoms are not the root causes.

Only to give up the HTTP protocol, using the "Long Connection" link, in order to accurately determine whether the user or from


Reprint Address: http://www.thinkphp.cn/topic/3217.html

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.