Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

PHP Check if a user is online

Tags:

php

timestamp

Could anyone tell me why this doesn't work? In my database lastactive is 2013-12-10 16:15:12, updates every time a user refreshes any page on my website.

I select it and set it as a variable:

$lastactive = $row[5]; 

Here's where I thought it should work, but doesn't. Using 10 seconds for testing.

if(time() > $lastactive+10){
    print('<div id="user_online_status" style="color: #aaa;">[OFFLINE]</div>');
}
else if(time() < $lastactive+10){
    print('<div id="user_online_status">[ONLINE]</div>');
}
like image 437
user3010610 Avatar asked Feb 02 '26 07:02

user3010610


2 Answers

You're comparing a unix timestamp to a MySQL datetime string. You need to convert it to a unix timestamp before comparing the two:

$lastactive = strtotime($row[5]);
like image 187
John Conde Avatar answered Feb 05 '26 02:02

John Conde


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.

like image 23
Robin Heller Avatar answered Feb 05 '26 01:02

Robin Heller