calculate the time logged in by a user - php

i want to calculate the time for which the user remains logged in on my site, for example if user A logs in at 10 am and logs off at 10:15 am then store 15 minutes time and if he again logs in then also calculate that time and add to this 15 minutes and shows his total time in the system.

Quick example I can give you.
First add the required field in your database. i.e. In your users table, have a field called 'totalTime' or something.
If you're using SESSIONS, keep a value $_SESSION["start_time"] when the user logs in, and when the user logs out take the difference of the current time subtracted by the start time and add it to the totalTime field in the database for the specified user.
Any variation of that should work.

You could have a loggedIn field in your table, and a totalTime field. When the user logs in, record the time in the loggedIn field. When he logs out, get the logged in time, calculate the difference, and store it in the totalTime field, and zero the loggedIn field.
If the user logs in and the loggedIn field is not zero, the user did not log out, add the difference between the current time and the last loggedIn value can be added to the totalTime (or zero added - you would decide on a policy) and the loggedIn field updated to the new log in time etc.

If you want to collect detailed information about users, and not use simple statistics that google paralytics provide, you have a couple options, none of which are perfect solutions for anything.
Option 1:
You can simply record the time when users click on your page. The issue with this is that there is no way to see how much time a user has spent on your last page. But overall it will provide a good estimate, but will be very costly if yo have over 1000 users.
Option 2:
Record the time when user enters the website, and then have javascript ajax call that will record the time when user either logs out or closes the page. This will work if you allow users to be in a single window only.
Option 3:
Have javascript execute every minute or so and tell database that user is still logged in. Almost all databases can do over 1000 queries like that per second. If you optimize it, change database engine or do anything else you can easily get to 10k-25k queries per second.
Option 3:
If you are charging people money per minute then you can wrap the entire thing in java, or flash. however it is also not very secure.
Bottom line is: There is no perfect way to do it. You will have to hope that users have javascript enabled and track their time using background scripts, or do the whole session thing and hope that users log out. Or Track everything click by click and hope that your algorithm works well enough.

The below solution would be the most efficient one
The log table should have userid, unique_identifier, start_time, end_time
Logging in to the website will add a unique identifier for that session. It can be random number of 12 digits.
A variable $default_duration = 1440; is defined to calculate the session exipry due to inactivity. This variable should be set according to your server settings. 1140 is 1140 seconds (24 minutes), which is the default session exipry time
On user login, lets say a user loggs in by 2PM, the end time is set on login as well, which will be 2.24PM. This will solve the scenario of a user's session expiry due to inactivity.
On each page load, the end time is updated with "Current Time + $default_duration"
If a user clicks on Logout button, the endtime for that session is taken from the current time. This records the exact duration of the user.
Incase if the user logout and logins again, it would have a different "unique identifier" and the log time is updated against it.

Related

How can I use MySQL and PHP to increase a value daily?

So I'm wondering how I can increase the value for the user by 10 daily or each time they log in?
I'm relatively new to PHP and have only made a login and signup system and need help learning.
You need a new column for each user in the database, this will store the value. You also need to store the last time they logged in (so you'll need a column for that). Each time they log in, in the login PHP code check to see if the current date is at least one day ahead of the last time they logged in. If it is, increase the value by ten; otherwise, leave it.

Session in PHP and Mysql

I want to create a page on which I can see, who is logged in on my site.
For every user after logging in I create a session, and send a query to change the row "Logged" in mysql from No to Yes.
Then, on the page I use PHP to show everyone, who has Yes set in mysql, and it works.
But, I have a problem, which occurs when someone close the browser without clicking Logout - the query doesn't execute and the Yes value in mysql stays...
What can I do to create a page like this?
Instead of having a boolean value for logged in or out, determine a reasonable amount of time for the session to expire (e.g., 1 month) and then add that amount of time to a timestamp and store that in the database as session_expires or something. Then you can check if the user's session has expired whenever you do your login checks.
Additionally, to manually expire the session (for instance if a user logs out) just set the session_expires field to a timestamp in the past.
EDIT
I didn't have access to a computer over the weekend, so I couldn't properly update my answer.
If you need to see active users, one thing I've done in the past is to use a last_seen timestamp field that updates any time the user does anything on the site. Then, on your "users logged in" page, just query for something recent like "last seen in the past 15 minutes."
You cannot do anything about that, but defining a timeout. That means your initial call after logging in that sets your customer row to "YES" should be triggered on every request (or to spare resources, every minute) to update a date column in that very customer row. If no update comes in anymore, you define that customer as "not logged in anymore" and update the column to "NO"
The fact that the user keeps on staying logged in is due to the PHP SESSION TIMEOUT which may be configured in PHP settings php.ini.
Have a look at http://php.net/manual/en/function.session-set-save-handler.php to learn how to set a session shutdown handler (that will be called once the session becomes invalid). When the shutdown handler is called, set your current session's "logged" to false in the database. Still, it may take up to 24 minutes (default value in php.ini for session timeout - session.gc_maxlifetime = 1440 minutes).
Decrease this value (session.gc_maxlifetime) to 2-3 minutes and have a ajax function on each of your pages keeping the session alive. This will definitely increase your server's load but you will definitely have a better representation of the currently active users. You can decrease the value from php.ini or by usig ini_set(‘session.gc_maxlifetime’,30); in your code.
Regards

count the time in different mode of a user during his login session

I want to store user login time.
After login, there are 4 modes
1. available
2. break
3. traning
4. email
When user select 1 of these modes, the timer of that modes start increasing.
then need to store logout time.
At admin end... admin can check the total timing of users in all individual modes.
So the question is that how to add timer and how that timers time changes in the database in 1 second interval?
get unix timestamp when user starts any mode and get unix timestamp when user stops. Subtract the former from latter to get total time
Refer to PHP time.
Set the initial link to input the current time. Upon logout, you will also log the time. Subtract the logout time, from the initial logon time.
As far as labeling the modes, you may set it up so that every individual mode has a different variable.

How to limit number of logins at a time?

Hello I have a website. created using php,mysql. I want to set a limit like.. only 10 user can login my website at same time. How can I do that kind of a setting? any body knows the solution kindly help me..
Use a database table to store the number of logged in users but you need to come up with some way of imposing a time limit on those users. I would suggest a field in the table which notes their last activity. When a new user attempts to login you need to apply some logic like this (pseudocode):
if(<10users){
login
} elseif(any of the users have no activity for 30 mins){
remove that user and login
} else {
inform user of no space
}
You would need to update the last activity every time a logged in user visits a new page.
Go read up on sessions in PHP, then write your own session handler - the first time as a learning exercise. Then write your own session handler again, fixing all the bugs from your first attempt and adding in the facility to count active sessions.
Note that the normal behaviour for session handlers is that the session data persists even after the session has timed out - its up to the garbage collector (and optionally the session loader) to clear up session data which is stale.
i would override php session handling and store user sessions in the database. you can find a simple tutorial here: http://www.raditha.com/php/session.php
this way you can simply check if there are more than 10 valid sessions stored in your database table. though you have to think about handling logouts and timeouts, as some standard timeout like 30 minutes might not work well in your application.
If you want 10 user logged on your site, disable the login box if there are more than 10 users logged in.
This presume that you have a table in the db that records the users that are logged in the site. The login procedure will write a new line in the table. The logout procedure will delete it.
Simply count the numbers of rows in this table to determine the number of users.
as answered above you have to maintain a table which will store the number of users who logged in,but whenever the user logs out then decrement that value....whenever a new user logins increment that value by checking it with ur limit

Is my method of auto-redirect-login page correct in PHP?

I have a community site where a user can have many friends. When displaying all of his friends, I want to include whether his friend is online or offline.
My method is, when user logs in, create a session and update the users table, on status column "online". If he click the logout button, then i will set the status to "offline". What if he close his browser without clicking the logout button? Here is what I want to do:
session_start();
if (!isset($_SESSION['LAST_ACTIVITY'])) {
// initiate value
$_SESSION['LAST_ACTIVITY'] = time();
}
if (time() - $_SESSION['LAST_ACTIVITY'] > 3600) {
// last activity is more than 10 minutes ago
session_destroy();
//direct to a php, say this user is idle and thus status = offline
header("location: update_status.php?user=".$_SESSION['username']."&status=offline");
// den redirect them to login page
} else {
// update last activity timestamp
$_SESSION['LAST_ACTIVITY'] = time();
}
Is this an appropriate way?
EDIT:
It would be helpful to see some easy sample code with how to check whenever a user is online and update whenever a user visits a page?
Do I need to include php?user=$_SESSION['userid'] in every link?
Well if you determine whether or not a user is logged out, simply by your online/offline column - then users closing their browser window (without hitting your logout link/button) will still be logged in.
The normal approach here is to keep track of when your users move around your site, storing the last time of when they navigated to a page. Then you set a predefined constant of what makes a user active (say navigating around your page within the last 15 minutes) - and then you use this on your SQL Query to grab every user that is a friend of the visiting person and has been on the site within the last 15 minutes.
In a SQL Query where you store your time as datetime (this is a query for MySQL) this could look something like:
SELECT col1, col2, col3 FROM Users WHERE DATE_ADD(LastActive, INTERVAL 15 MINUTE) > NOW() AND UserIsFriendOfCurrentUser
Of course your query would need adapted to fit your setup better, but hopefully you get the idea.
In my Opinion this will not work. When the User closes the Browser, the code you put here will never be called.
A possible way would be to save the last time the user was active in the database, whenever the User calls a page. If the Users last Activity was longer than say 5 minutes ago, you could count him as offline, and show this to other Users.
I think that phpbb3 does it that way...
Getting an Event when the User closes the Browser is heavy and does not always work.
After the header location redirect, definitely put this line:
die();
Not all user agents (browsers, web spiders, etc) will listen to your redirect header. Killing the script is the only safe way to make sure they don't get the rest of the page.
As far as I understand your solution is the user still marked as online even when the last time the user was on the site is more then 10 minutes ago.
You should save in your database, the last time an user was active on your site. When a user looks then on the list of friends you get also this time and look if that is more then 10 minutes ago, i.e. the friend is inactive.
The best way to do this is to store activity times for logged in users. When they navigate to a page, or perform an action, update their "last activity" time in the database with the current time. If this time falls outside of a threshold (say, 15 minutes), then you can class the user as no longer active.
In our project we use this technique:
every user after login is being associated with session id.
browser sends an "activity-request" with AJAX by timer.
a lightweight server-side script updates last activity in DB, searching
user by session id.
cronjob updates all timed-out users, marking them as offline
(actually session id gets empty), and
executes logout routines for every
user to avoid corrupted data on
business-level layer.
What happens to user?
Until user closes his browser - activity is being updated. After closing the browser user gets timed out and marked as offline. When user tries to reach any location which requires authorization - the first thing we try to do is to find him in DB by session id, and if not - he just can see nothing but login form (i.e. include(); exit();).
Bad thing - tabbed browsers use the same session id for each opened tab in the same window. But our project is a game and multi-users from one browser are not allowed. Actually it's a very rare situation wher 2 or more users try to login from different tabs of one browser...
I see a couple of problems in your code:
if (time() - $_SESSION['LAST_ACTIVITY'] > 3600) {
// last activity is more than 10 minutes ago
session_destroy();
//direct to a php, say this user is idle and thus status = offline
header("location: update_status.php?user=".$_SESSION['username']."&status=offline");
}
In this piece of code you destroy the session and then get the username from the session you just destroyed.
By the way, if I understand your question, you don't get the intended behaviour with this code.
You check if the user is just accessing your site (owner of the session you start) has been idle form more than 10 minutes and, if true, you disconnect him just now that it tries to reenter in the site.
You shouldn't use $_SESSION for storing the last activity time. Every time a user goes to a page, update a column called last_activity with the current time in the users table:
<?php
session_start();
$userId = (int)$_SESSION['user']; // make sure it's an integer
$db->exec('
UPDATE users
SET last_activity = NOW()
WHERE id = ' . $_SESSION['id']
);
//...
When you retrieve your list of friends, add an if statement to check if they are online (this is the MySQL version):
SELECT
u.user_name, u.name, etc,
IF(
UNIX_TIMESTAMP() - UNIX_TIMESTAMP(u.last_activity) < 300,
1, 0
) as online
...
The 300 is seconds so 5 minutes. Adjust this as you see fit. Then your friends can be accessed like so:
$friends = $db->query(/* above SQL */);
foreach($friends as $friend)
{
if($friend['online'] == 1)
// online specific stuff
else
// offline specific stuff
}
Database sessions may be a good way for you to manage who is online and who isn't. Theoretically they should expire on their own. I wrote a how-to on my blog about it, you can read more at http://brennydoogles.wordpress.com/2011/09/06/taking-control-of-your-php-sessions-using-database-sessions/
This also has the added bonus of allowing you to kill a user session remotely if you need to :)

Categories