简体   繁体   中英

How can I update a mysql field when my user loses connection to my site?

I want to update a mysql table field value to "offline" when the user loses connection or logged out from my website. Is it possible? if yes, then how?

No, it is not possible.

Instead of using a field and setting it to online and offline you should make it an INT field instead. Every time the user interacts with your website just update the field with the current timestamp ( $_SERVER['REQUEST_TIME'] ). Using the field you can then infer the user's status by seeing how long it has been since she was active (eg <=30min is online, and >30min is offline).

First, using PHP sessions, assign a unique random ID to every visitor. Then create a DB row containing this ID, the time the ID was created and the time it was last seen online.

Then, every 60 seconds or so, using jQuery's .load(), load a PHP script from the server which just updates the last_seen field in the mysql database. Job done.

To avoid overflowing, make a cronjob, or using random, clean-up your database every X requests or minutes.

Using PHP Session will help here. Whenever user logs in, update the PHP's session_id() in database field, As well all know that PHP store session data in tmp folder. You can scan this folder using cron job for alive sessions. Generally session file look like sess_session_id().

The Algorithm is given below

  1. User Logs In
  2. Update Session value in database
  3. Update login status as OnLine

Run a cron job every 1 minute, Write CLI programs so that you don't need to make unnecessary HTTP Requests. This CLI program will scan the table containing session id and you need to search the same (session_id prefixed with sess_) in tmp folder. If file exists that means user is online and if file doesn't exist then user is offline.

I Hope this helps.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM