Using timestamp to show active users? - php

I am working on a quite simple custom made content management system (CMS). There is a database table containing usernames, passwords, emailaddresses and a date/time field showing when the user logged in for the last time (I used "NOW()" in the query when updating).
When an user successfully logs in, the script will update a table in the database and sets the new time (using NOW()).
Now I would like to show which users are currently logged in, in the past 5 or 10 minutes. I have no idea how to accomplish this, therefore I am calling for your help. On the internet I read I need to do this with a timestamp, but I have no idea how this works.
I need to know how to set a specific timestamp.
I need to know how I can check in PHP if the user has been logged in in the past 5 or 10 minutes so I can display their names somewhere.
Thanks for your help!

1.
Why do you need to set a custom timestamp? Using NOW() is all you need.
2. This query will find all users where the column latest_login is in the past 10 minutes:
SELECT * FROM users WHERE latest_login >= DATE_SUB(NOW(), INTERVAL 10 MINUTE)

ok this is quite simple
1ts - convert your date into timestamp using function mktime (check google , lets say $date)
2nd - use function time() to get current timestamp (let say $now)
3rd if ( ($now - $date) > ( 5 * 60 /* 5 minute */ ) ) { return "not login" }
else return "login"
timestamp counts seconds so 5*60 is 5 minutes

Related

How to calculate the total time logged in the system?

I am using CodeIgniter and I am calculating the total time from the dates.
Explanation:
What I am doing is, Every login I am inserting the last_Ativity date and time in the database using below code.
$data_login= array('emp_id' =>$result->id ,'last_activity' =>date("Y-m-d H:i:s", STRTOTIME(date('h:i:sa'))));
$this->db->insert('tbl_current_login',$data_login);
last_activity time continuously updating if the user still in the system . (I am using ajax to update the datetime. I haven't shared that code).
Now I have to calculate the total time of the specific user for a single day(current date).
For example- emp_id 26 logged in twice so I have to calculate the time
First-time login date and time:-2018-09-17 07:27:55
Second-time login date and time:- 2018-09-17 07:35:22
It will increase depending upon how many time the user logged in.
I am confused about the time. Am I on the right path to calculate the total hour login in the system?
Should I use an MYSQL query or PHP to calculate? I need some idea.
Would you help me out in this?
This is what I would do
last_activity time continuously updating if the user still in the system . (I am using ajax to update the datetime. I haven't shared that code).
Before you update the row.
check if a row for activity exists
if it does, get the timestamps for the date and subtract the current time (the one you are changing last_activity to, from the one stored in the DB) take that number and add it to an integer column named something like elapsed time (you would have to add this to the DB)
if not then enter a row with 0 elapsed time ( depending how you put the first row in, maybe on login) this may never be an issue.
For the timestamps, you would do a select to get the current row. Take the datetime field and use either
$time = strtotime($row['last_activity']);
OR
$time = (new DateTime($row['last_activity']))->getTimestamp();
Then you simply do the same thing to the date you are going to replace that with and then subtract to get the difference in seconds.
$elapsed = time() - $time;
And then add that to the current rows value, and save it. This way you can keep track of a running total in seconds of the time they spend during that session.
Then when you need to count the total time its a simple matter of doing
SELECT SUM(elapsed_time) FROM {table} WHERE DATE(last_Ativity) = :date
If you were dealing with just two date time fields in the DB it would be easier to just get the difference of those, but sense you already have code to constantly update the last active field this would require less work in the long run IMO.
Option2
The other option is to add another Datetime field to put a start time or login time in. Then when you query you can convert them to their timestamps and subtract to get the difference.
This makes the SQL harder (when doing the SUM ), I can't really think off the top of my head how I would calculate the elapsed time on multiple rows and then sum them up. But it does simplify the PHP quite a bit. So which ever way works best for what you need. Think about if you need the utility to know when they logged in, or if you just want an easier way to calculate the time they spend.
Something like that.
Assuming that the only log happens based on user actions, and so, after 15 minutes (for example) the user is assumed logged out
And assuming you'd want daily total, the solution should be something like this:
SELECT
first.emp_id,
SUM(TIMESTAMPDIFF(MINUTE,first.last_acivity, DATE_ADD(IFNULL(last.last_acivity, first.last_acivity), INTERVAL 15 MINUTE))) as logged_minutes
FROM
(
SELECT
la1.*
FROM
last_acivity la1
LEFT JOIN last_acivity la2 ON
la1.emp_id = la2.emp_id AND la1.last_acivity < la2.last_acivity
AND la2.activity =< #date0
WHERE
la1.last_acivity >= #date0
AND la2.login_id IS NULL
) first
LEFT JOIN
(
SELECT
la1.*
FROM
last_acivity la1
LEFT JOIN last_acivity la2 ON
la1.emp_id = la2.emp_id AND la1.last_acivity > la2.last_acivity
AND la2.activity =< #date0
WHERE
la1.last_acivity >= #date0
AND la2.login_id IS NULL
) last
ON
first.emp_id = last.emp_id
GROUP BY
emp_id
In this query need to set the date seperately:
SET #date0 = DATE(NOW()) ;
To get the first record of the day, or the last, we need to LEFT join the table to itself, on the same emp_id BUT witn with an inequality, which will get for each emp record its ancestors or predecessors
When we add the NULL condition we bring the we get the edge case: first or last
What's left then is just calculating the minutes between the 2 tables
Since I assumed no log out record occurs, I treated the case when the first and last logins are the same, or no last login

php detecting if user is offline using setinterval?

Hi guys i'm creating an online/offline system using PHP.
When user is logged in sessions are set and user is considered online and I run a set interval function that logs time(); into my database every 10 seconds.
setInterval(function(){
//update time every 10 seconds
$.get("timeupdate.php");
}, 10000);
I need some direction please in my next stage when I have to detect when the user is offline and I am slightly confused.
Do I run an if else statement?
$time = time();
$time2 = $row['time_update'] -> last updated time in my database
if($time > $time2 + 20) {
echo "user is offline";
}
because of the 10 second setinterval if $time ( the current unix timestamp) is greater than the last updated unix timestamp then user is offline.
am I right? and how would I go about implementing this display offline file?
Why implement the logic in PHP when the data in your database? If you're using MySQL date times....
SELECT last_seen_seconds_ago
, IF($MAXINTERVAL*1.05>last_seen_seconds_ago, 1, 0) AS status
FROM (
SELECT UNIX_TIMESTAMP(NOW())-UNIX_TIMESTAMP(time_update)
AS last_seen_seconds_ago
FROM yourtable
WHERE user='$user') ilv
(allows a 5% variance)

Limit the access of a function to once every 24 hours (PHP and MySQL)

I would like to limit the access of a function i've created to once every 24 hour based on the users IP address.
I would also like the PHP script to delete the MySQL record if it's older than 24 hours.
If the user already has used the function within 24 hours, show them a message and prevent the script from continue running.
If the user already has used the function but 24 hours has passed since he used the function, delete the MySQL record and let the script continue running.
<?php
$ip = $_SERVER['REMOTE_ADDR'];
$con=mysqli_connect("domain.com.mysql","domain_com","domain_password","domain_database");
$result = mysqli_query($con,"SELECT * FROM ipblock WHERE ip='".$ip."'");
while($row = mysqli_fetch_array($result));
if($ip == $row['ip']) //and code for checking how old the record is
{
// The user has used the function within 24 hours, kill the script.
echo "Come back in 24 hours";
exit;
}
else
{
// Looks clear, let them use the function
$MyFunction = true;
}
?>
I'm lost and as you can see i am also missing some statements for deleting old records (-24 hours)..
Could anyone provide me with an example of how to do this?
Thanks
Firstly store the IP and Access time as a pair in a table. Then you check is simple to see if there are any records in existence where the IP matches and the timestamp is less than 24 hours ago.
Before the function runs, complete an INSERT ... ON DUPLICATE UPDATE, and have the IP address as the primary key in the table.
The removal of old entries is then less of a priority and you can schedule this to be whenever convinient and remove entries where the access time is greater than 24 hours ago.
Store the access time as a myqsl date time, and do the comparison using the where clause:
WHERE accesstime >= DATE_SUB(NOW(), INTERVAL 1 DAY)
I'd create a table with function load
Store IP address and timestamp
When user loads the page, before running the function, select for IP adress and timestamp < 24 hours previous.
If you run the function: Store the users IP
No need to delete older records. But you could lik this to the verification function: delete all events older than 24 hours whenever the function is called for. Or set a cronjob to run every 12 hours to delete all older function load records
Basically, you can just create a timestamp field in the database. Then you compare using timediff() the stored values with the value of now().

Online or offline function PHP

I'm working on a "community". And of course I would like to be able to tell if a user is online or offline.
I've created so that when you log in a row in my table UPDATE's to 1 (default is 0) and then they're online. And when they log out they're offline. But if they don't press the Log out button, they will be online until they press that button.
So what I would like to create is:
After 5 minutes of inactivity the row in my database should UPDATE to 0.
What I'm looking for is how to do this the easiest way. Should I make an mysql_query which UPDATE's the row to 1 every time a page is loaded. Or is there another way to do it?
Instead of using a boolean "Online" field, use a DateTime. When a user makes a request to the page, update the DateTime to NOW(). When you are gathering your list of current users online, your WHERE clause would be something like WHERE lastSeen > DATE_SUB(NOW(), INTERVAL 5 Minutes)
Update: To retrieve individual online status.
select if(lastSeen > date_sub(now(), interval 15 minutes), 1, 0) as status from table where userid=$userid
This tutorial is quite handy: Who Is Online Widget With PHP, MySQL & jQuery
Well, if you don't want to set up a cron job, that would execute some code every 5 minutes, you have no options. But, actually, I think the following approach would be much more efficient:
Change your 1/0 column to timestamp
On each user request update that timestamp to current DateTime.
When checking for active users, check if that timestamp is less than 5 minutes from now
This way you'll be having actual data on users and no recurring queries - just one additional update per request
If you will update the row only on page load, then some of information would be incorrect.
Let's assume that user have opened page and is writing really long text or something. He is doing it for half an hour now. And your database ny now is already updated and he is counted as offline user.
I would write javascript that pings you back each 5 minutes, if opened tab is active.
This ping updates database field 'last_activity' to NOW(). And to count online users, or check if user is online you'll need to compare 'last_activity' to NOW() minus five minutes.
Simpliest ways (IMHO):
You can count sessions in session_save_path() dir.
you can store last visit timestamp in DB, and count rows with (timestamp > current_timestamp - somedelay).

PHP and SQL Social Networking - User Online

I want to set up online detection on my website.
I have a row in my user table where the last login datetime is stored. Every time a user visits the site, his login date updates and user online row sets to 1 (1 - online, 0 - offline).
How to change the online row to 0 (offline) if the last login was 10 or more minutes ago? The aim is to find difference between dates.
cronjob every 10 minutes?
UDPATE users SET online = 0 WHERE login_date > (NOW() - INTERVAL 10 minute);
just to each user add a last_seen timestamp to there row so that when you do your user is authed check you can update the time
if(logged_in())
{
update_user();
}
function update_user()
{
//UPDATE users SET last_seen = unix_timestamp() WHERE uid = X;
}
Then you can do for you users:
SELECT * FROM users WHERE last_seen > (unix_timestamp()-300)
To get the last 5 mins.
If you want to show the users who have been online within last 10 mins then the best method is to include the datetime condition in the sql query.
Save the last login time as timestamp, then you can easily compare it with the current time and tell how much time has passed since.
Depending on the size of your user table, you can run the check of those who are still supposedly online every time somebody calls your website.
A different approach is to store active users in buckets, labeled with the last login time, you can then easily reset all users that are in buckets older than 10 minutes.

Categories