Online or offline function PHP - 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).

Related

Automatically update data in sql for a webpage

So I'm a software Development student and for my web class I created a project that uses among other things Php and SQL; In this project, users can create posts and other users can comment on them.
The thing is I want posts to only be available for a certain period of time.
Then I have an SQL table named 'Posts' and they have a column named 'Status' (you know, if the status it's 0 they're not available and else they are.)
When a user creates a post I make SQL:
INSERT INTO posts *All the post data*, I set the Status to 1 and make a TIMESTAMP to register the date of creation of the post. I want that a week after the date registered in the Timestamp changes the status column to 0 but I don't want it to be with a page request (I need it to be automatic) and I want the user to be notified via email or something.
Can it be made with some python CGI that checks the date, updates the Status and sends the email or is there a better/easier way to do it?
Thanks a lot for your help :)
You dont need the status 0/1 AND the timestamp column, if all you want to do is show a post for a set period of time.
Just use the timestamp column and amend the queries that fetch the posts to only show those posts that are < 7 days old (or any period you decide)
EG
SELECT * from posts where timestamp_col < DATE_SUB(NOW(), INTERVAL 7 DAY)
or something similiar that meets your needs
Turns out the best way to solve this was using Cron Jobs.
I run a PHP script every day and I modify the posts which are exactly 7 days old, using
UPDATE Posts SET Status = 0 WHERE DATE(timestamp_col) = DATE_SUB(NOW(), INTERVAL 7 DAY)
And then I iterate through the affected rows emailing the users.

MySQL get data older than 30 minutes and perform some tasks

I am trying to make a coupon system, but I got stuck with something. I want to make a function that gets all data from coupon_session where the time (datetime) is older than 30 minutes. For each of the results, I want to fetch the "code" from the row, and after that I want it to delete the row.
I've already figured out how to retrieve the data, but the rest is kinda hard for me. Could you guys help a bit?
This is my code for fetching all > 30 min old rows:
mysql_query("GET * FROM `coupon_session` WHERE TIMESTAMPDIFF(MINUTE,time,NOW()) > 30");
The code to fetch what you want is:
select cs.code
from coupon_session cs
where time < date_sub(now(), interval 30 minute);
Deleting is another problem, because the value of now() changes. You have several choices, such as:
Get the list of ids to delete in your application and delete those (probably the safest method).
Calculate "now" in your application and use the same value for the select and delete (also safe).
Calculate the maximum time returned by the select and use that for the subsequent delete.

Checking if the user has logged in the last 24 hours

I'm currently developing a "user rewarding" system in my website to reward the active users with a given virtual currency (points for example)
I'm having a problem thinking of a way to acomplish that.
I know that I would have to compare timestamps, but I have no idea when I should create the base timestamp, which I would use as the base for my calculations. I think I may not be explaining my question properly, so I will say it in a short manner: How can I check if the user has logged in the last 24 hours. When to create to create the timestamps that I will use for my calculations.
Thank you in advance for all of your answers.
I have a last_activity column in my users table
I'm just going to use some short-hand for this one:
OnRegister (to void giving instant points on first login):
user->lastPoints = now();
OnLogin:
if (user->lastPoints - now > 24h)
{
if (user->lastPoints - now < 48h)
{
user->rewardPoints();
}
user->lastPoints = now();
}
Hope this is what you're searching for.
Without knowing your application structure, it's hard to be specific, but update a 'last_activity' (or similar) field in your user table on occasion. Then check if that last_activity value is older than 24 hours.
Add some logic so the last_activity only gets updated every 15 minutes or so, and you won't be doing an extra DB write every page load.
Well you'd just have to store the timestamps each times your users log in. But if you want to check if they were online no matter if they had to login or not, you'd have implement an update to the timestamp on every page. You should also store the last update time in the cookie of the user so that you don't update at each page load but every ten minutes or what not.

PHP Login/Logout If Session Timeout = true Do Something

I have a script that will login and logout a user. It works perfectly. Now I have like a widget that counts how many users are registered and activated as well as how many users are online. I do this by having a field in my users database that says online = 1 or 0. When the person logs in, online = 1 and logs out online = 0. Now I haven't taken into account that this field is only being updated because the user is doing something. I haven't taken into account that the session would timeout.
How can I make a function that says something like if session timeout = true then update users set online=0 where username=$username and user_id=$user_id.
In your database table, add another column something like last_seen. Update this every time you see your users online. After a certain period of inactivity, they will be marked as inactive. In fact, I suggest you replace your online field with this.
For example,
ALTER TABLE users CHANGE COLUMN `online` `online` DATETIME; -- SAMPLE SQL query only
To check how many users are online:
SELECT * FROM users WHERE online>(NOW()-INTERVAL 1 HOUR); -- SELECTS all users online in the past hour.
If the user logs out, you can simply set the online = NOW()-INTERVAL 1 HOUR. Or, you can also retain your previous online field and you can check if the user is idle (using my suggestion) OR online=0.
Instead of trying to use a boolean value to see if somebody is logged in, try using a TIMESTAMP. Then you can perform more accurate logic based on how long somebody has been away. If the last time somebody has loaded a page on your website was 30 minutes ago, do you think they're online? Do you even think they're at their keyboard?
The session will only timeout if you want it to do so. This question is really a duplicate of 'How do I expire a PHP session?'
Code is only executed when a php page is served, so you will need to track the last time a user was active my using a session variable to track the last time a page was served to that user. Then, whenever serving any php page to the user, check to see if the timeout period has elapsed and log the user out if it has, see link for examples.
Add lastOnline field which stores the timestamp of last user activity.
Have some ajax function on the page which updates the timestamp every "n" seconds.
To check if user is online - check both: online field and timestamp. If timestamp was updates more than "n" seconds ago - user is offline even if online field is equal 1.

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