One solution I can think of right now is to use time().
Syntax:
$timestamp = time();
$timeout = $timestamp - 900;
This cannot detect if a user closes the browser. However, if you are looking for some ways to detect if a user is actively browsing your site, this would definitely help. How does it work?
Like for an example, John Doe visited this specific link from your site
http://website.com/chat.php.
In your php coding, you will have to append a new timestamp record in your database together with user's IP address.
MySQL Table record should be like this: (John Doe IP Address -> 00.000.000)
Tbl name: active_users
IP ADDRESS - TIMESTAMP
00.000.000 - 0903100
00.000.000 - 0904100
00.000.000 - 0906100
Everytime "chat.php" is loaded either by John Doe or by someone else, a function (let's call this removeInactive function ) will get the latest timestamp. A conditional statement will automatically detect and remove expired timestamp from your database. This way, you can keep track on your record if John Doe is still active in your site disregarding the fact the he closes the browser or simply left w/out logging out.
removeInactive function will do the following task everytime you call it in any particular page:
- if John Doe's timestamp is not yet expired, simply append new timestamp record
- detect and remove expired timestamp from active_users table
- display the latest record of active_users table
Here are some codes you might want to know:
Code: Select all
# Fetch Time
# $timeout value is based on seconds, minutes and hours.
$timestamp = time();
$timeout = $timestamp - 900;
# To insert new timestamp
$insert = mysql_query("INSERT INTO active_users (timestamp, ip) VALUES('$timestamp','".$_SERVER['REMOTE_ADDR']."')") or die("Error!");
# To remove expired timestamp
$delete = mysql_query("DELETE FROM active_users WHERE timestamp<$timeout") or die("Error!");
Hope this helps.