I'm Italian, and i'm not good in English, but I Try to explain what i want to ask to you :)
I'd want to ask you a question about PHP and Sessions stored on the server.
I'm making a Play by chat online game using php and mysql.
What I need is to detect, using php, expired sessions for inactivity.
While an user is logging into the game, I update a table on a DB . This column that I update is the timestamp of the latest action done by the user. Then, i start a session for the client X. If this column is empty, it means that the user is logged off .
If an user do the logout correctly ( a button inside the game ), with php i destroy the session and i update the column of the DB with an empty timestamp, so the user results correctly logged off, but if there is a crash of the browser?
How can I detect that a session has been destroyed by the crash of the browser?
Thank you :)
you could store the connection ID in a seperate table, run a loop that periodically checks those connections for messages the client periodically would sent to denote activity
if the time difference is larger than the message update interval by a certain margin, you would drop the connection and/or update the tables
You have to set a "timeout", for example 10 minutes (600sec)
So, for any action of a user you check if he is current active by the difference of date_last_action and now().
For exampre.
Login : 2014-03-27 15:49:00
Last action: 2014-03-27 15:51:00 (only 2 minutes from the last action
[login])
Last action: 2014-03-27 16:21:00 (over time, so clear the db record,
delete his session)
$date_now = time();
$date= DATA VALUE OF LAST CURRENT USER ACTION;
$date1 = time();
$date2 = mktime($hh,$ii,$ss,$mm,$gg,$aaaa);
$dateDiff = $date1 - $date2;
$fullDays = floor($dateDiff/(60*60*24));
$fullHours = floor(($dateDiff-($fullDays*60*60*24))/(60*60));
$fullMinutes = floor(($dateDiff-($fullDays*60*60*24)-($fullHours*60*60))/60);
$deadline_in_minutes=10;
if($fullMinutes>$deadline_in_minutes)
{
//do logout clear session
}
Ciao!
Related
I currently have a problem with my laravel(4.2) app.
I want to update my database when the user is offline by the end of session (Automatic).
So I put the lifetime session to 1 minute for testing.
I create an event file :
<?php
Event::listen('auth.login', function($user)
{
$user->is_online = 1;
$user->save();
});
Event::listen('auth.logout', function($user)
{
$user->is_online = 0;
$user->save();
});
Everything works perfectly when I log in or log out manually but when I get automatically disconnected by the end of the session it does not work.
If you have an idea I would appreciate
Thanks.
You have to detect if the session has ended by comparing it with the current time. For instance:
if ((time() - Session::activity()) > (Config::get('session.lifetime') * 60))
{
// Session expired
Event::fire('session.expired');
}
Hook into the session.expired event and do whatever you want.
You cannot detect when a user closes their browser or navigates off your site using PHP
Instead, your best bet is most likely to store each user's last activity time.
Create a column in your user table along the lines of 'last_activity'.
Whenever a user loads a page, update their last_activity to the current time.
To get a list of who's online, just query the database for users with last_activity values more recent than 10 min or 20 min.
you can set session time using this
$_SESSION['time'] = time();
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.
Ok basically I have a form that a user submits but I need a 'cool down timer' so that the user cannot submit it again for a given amount of time.
I could not find out how to do this in php which would be preferred if possible.
Thanks in advance.
You can store in database (example: MySQL) timestamp of last successful submit and on every submit check if value from database + cool down time smaller or equal to current timestamp.
You can get current timestamp in PHP with time().
You have to use sessions for that!
When the user submits the form you have to add the timestamp to his sessions:
$_SESSION['last_submit'] = time();
Now when he submits the form again simply compare the timestamps, e. g. :
if(isset($_SESSION['last_submit']) && ((time() - $_SESSION['last_submit']) < 60 * 5)) { //time in seconds! 60 seconds = 1 Minute and 1 minute * 5 = 5 minutes!
die('Wait a few');
}
$_SESSION['last_submit'] = time();
// regular form processing here!
What we do here is to check first: is a previous timestap set? And then if time() - lastsubmit is less then 5 minutes.
If these all return true, the form was submitted to "early" and we simply die. If not we refresh the sessions' s timestamp and can move on.
And of course don' t forget to start the session!
session_start();
On the very top of the page!
As I' ve read in a comment (thanks again!) a user just could use another browser or clear the cookies. To prevent this (as good as possible) you have to take the IP into account as well.
For this you have to use a server-side database! Store the client' s IP into this database with the timestamp along and then in your if statement you don' t need to get the timestamp from the session, but from the database. Use the client' s IP to get the assoc. timestamp.
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.
i am new in php.. i want to delete the user automatically if he does not attempt login in 30 days.
for example
if user login on "10-02-2012" ,
and if user doesnot login for next 30 days
then system should automatically delete his account.
if user again login on "15-02-2012" ,
then limit should be for next 30 days i-e "15-03-2012"
please help me i am very new in php
i have no idea how to store the date when user attempt to login.
You want to have a date field in the user table and a query that sets that date to CURDATE() whenever your login script runs. Something like:
UPDATE 'users' SET 'lastlogin' = CURDATE() WHERE 'userid' = '$userid';
Have a crontab that runs once a day (or however often you want) that queries all the fields that are 31 days old and deletes them:
DELETE FROM 'users' WHERE 'lastlogin' < CURDATE() - INTERVAL 31 DAY
Log the last login date in a Database.
Write a script which searches and deletes users where the last login was more then 30 days ago.
start the search and delete script with a cron job
Here's a tutorial on building a login system:
http://www.phpeasystep.com/phptu/6.html
Your solution would add to the tutorial by adding a DATETIME field named "last_login" to the members table. Whenever someone logs in, you update the last_login field with a database query like:
UPDATE TABLE members SET last_login = CURRENT_TIME WHERE id = xxx LIMIT 1
Then you can run another database query once a day to delete inactive accounts, customizing the deletion date as needed:
DELETE FROM TABLE members WHERE last_login < '2012-04-01 00:00:00'
it's very simple.
create a field in the DB table that stores the most recent login date.
write a script run every night at midnight that checks the login date against the current date.
the great thing about this is date objects allow you to easily compare dates easily.
here are some links that will help:
http://php.net/manual/en/function.date.php
http://www.w3schools.com/sql/sql_dates.asp
best of luck! it's pretty straight forward I have done it many times im sure you wont have much trouble.
In your data base, where user accounts are stored, you can store the last time they logged in using one of the built in MySQL date/time data types. In your PHP you can update this to the current time with another MySQL command. This page will get you started: http://dev.mysql.com/doc/refman/5.5/en/date-and-time-functions.html
As for deleting a user, you will want to set up a cron job/scheduled task, that will delete this user by checking the date and seeing if it is 30 days ago.
You can add two field for users table
created : date when user registered
login_date: date update on every login by user.
And you can use cron Job which run automatically (run a php file which path set in it) on selected time. you can run it every day on a fixed time. and if found both created and login_date same then delete that user from database. You can set cron job from your cpanel.
thanks
set up cron job for once a day and check who didn't logged in from last 30 days to current time / date you can use timestamp or date for last login