Whats the Easiest Way to Determine If a User Is Online? (Php/Mysql)

Whats the easiest way to determine if a user is online? (PHP/MYSQL)

Don't bother with figuring out the differences between time zones—that's not necessary.

Whenever the user accesses a page, set/update a lastActiveTime field in their record of the Users table. Then, do a COUNT for all users having a lastActiveTime within the last 5 minutes. Anything more than this, and they can be considered "offline."

If you use your server-time, via the NOW() function in MySQL, you'll avoid the need to deal with time zones. This is the standard way of tracking how many users are presently online (meaning, active within the last x minutes).

Constantly Updated

If you would like to know they are still active (even when they're not jumping from page to page), you could include a bit of JavaScript to ping your server every 60 seconds. It'll work the same way as my original suggestion, but it will update your records without requiring users to be frantically browsing your site at least once every five minutes.

Original 2009 Code

var stillAlive = setInterval(function () {
/* XHR back to server
Example uses jQuery */
$.get("stillAlive.php");
}, 60000);

Updated 2022 Code

We can use fetch and promises today to more precisely issue these calls. Fetch will replace our earlier XHR approach using jQuery. Fetch returns a Promise, which we'll use (via the await keyword) to defer timing of our next call. Once the call to stillAlive.php is complete, and a response has been retrieved, we'll setup the next ping for 60 seconds later.

(async function ping () {
// Asynchronously call stillAlive.php
await fetch( "stillAlive.php" );
// Issue this call again in 60 seconds
setTimeout( ping, 60_000 );
}());

How to see if a user is online in a website with php and mysql driven databases?

You don't need the online/offline flag, you just need to save the last activitity time. When displaying the user status, if last activity time is less than now+15 minutes then user is online, offline otherwise.

Check if user is online from mysql?

I'd recommend storing the logged in user information in the $_SESSION variable.

PHP automatically makes use of the COOKIE value to store the $_SESSION values on the server side, only accessible by your PHP scripts making them slightly more secure.

So, you could store the user id in a SESSION value on one page:

$_SESSION['user_id'] = 1;

... and then you can retrieve this on any other pages:

if (isset($_SESSION['user_id']))
{
// Logged in
}
else
{
// Not logged in
}

How to detect online and offline users php mysql?

Here is back-end PHP and MySQL code, i am using PHP Adodb library. Now after logging into a site you can run this code to view online users

MY SQL CODE

CREATE TABLE `useronline` (
`timestamp` BIGINT(20) NOT NULL DEFAULT 0,
`ip` VARCHAR(40) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
`file` VARCHAR(100) NULL DEFAULT NULL COLLATE 'utf8_unicode_ci',
PRIMARY KEY (`timestamp`),
INDEX `ip` (`ip`),
INDEX `file` (`file`)
)

PHP CODE

// expired time
$timeoutseconds = 600;

//get the time
$timestamp = time();
$timeout = $timestamp-$timeoutseconds;

// insert new user to table
$sql_checkip = "select * from $GLOBALS[db_sp].useronline where file = '".session_id()."'";
$rs_checkip = $GLOBALS["sp"]->getRow($sql_checkip);
if(!$rs_checkip['file']){
$sql_in = " INSERT INTO $GLOBALS[db_sp].useronline SET
timestamp ='$timestamp',
ip = '" . getenv('REMOTE_ADDR')."',
file = '" . session_id() ."'

";
$GLOBALS["sp"]->execute($sql_in);
}

//delete values when they leave
$sql_del = "DELETE FROM useronline WHERE timestamp < $timeout";
$GLOBALS["sp"]->execute($sql_del);

//grab the results
$sql_useronlines = "SELECT DISTINCT file FROM $GLOBALS[db_sp].useronline";
$useronlines = count($GLOBALS["sp"]->getcol($sql));
return $useronlines;

PHP Check if a user is online

Replace your SELECT statement from:

SELECT lastOnline FROM user

to something like...

SELECT UNIX_TIMESTAMP(lastOnline) FROM user

that's it. You're currently checking the Date string against a UNIX Timestamp.

How to know if the user is still online on the website or offline

You have three options:

  1. You can assume the user is offline if they don't load a new page within a specific period of time (e.g. 10 minutes). This would be done by keeping a "last page load time" for each user on the server.

  2. You can have a script on your pages that fires off an AJAX call every so often to tell the server "I'm still here" - this would use the same logic as #1, but would be somewhat more reliable.

  3. You can use a page-unload AJAX call to tell the server when the browser is unloading the page, and mark the user as offline until they load another page.

Check if user is online or not .Too many ajax requests

Cron Solution

  • Make it so every-time the user visits a page/browses the site you update them to active = 1 and put in a time=time();

  • Create a cron script to update all users who's time is lower than a specific amount, you can have 1 cron to run every 15 minutes, which can include both queries (as it will tick those at 5 hours when the time hits)

Queries in the cron file

UPDATE users SET active = 2 WHERE time < (time() - 900);
UPDATE users SET active = 0 WHERE time < (time() - 18000);

If you need some form of real time state, say the user visits a page but does not leave it (and does not close browser), then you can create a set interval to update them, say every 15 minutes.

The key is, giving yourself some kind of average estimate. Trying to detect who exactly is online at a per second basis in realtime is not good with ajax, it is not built for that purpose and you should be looking into something like NodeJS/Websockets. If however 5, 10 or 15 minute leeway is an acceptable "guess", then its very simple.

At query solution

Alternatively
If you cannot use cron (shared hosting), then you could base it completely off time rather than active state. Thus when you query to show who is online, you would do an if condition within the SQL query to determine if their active state should be a 0, a 1 or a 2, have a read up on http://dev.mysql.com/doc/refman/5.0/en/control-flow-functions.html for that

select 
username,
CASE
WHEN active_time > (UNIX_TIMESTAMP(now()) - 900) THEN 1
WHEN active_time > (UNIX_TIMESTAMP(now()) - 18000) THEN 2
ELSE 0
END AS active_state
FROM users
ORDER BY active_time DESC

If you dont want to query offline, you could add WHERE active_time > (UNIX_TIMESTAMP(now()) - 18000), the reason not to where on active_state is because that needs to be calculated before where can be done, whilst active_time is a field and can be filtered first before the select calculation, cutting down MySQL resources.

Store your active time with a unix timestamp, either using UNIX_TIMESTAMP(now()) or PHP's time()

This will return user with their respective active states, this is on a select though but you could filter the results purely based on time and not rely on a active state being a specific number.



Related Topics



Leave a reply



Submit