Email Id : phpmk888@gmail.com
Add caption |
what you do is that you add an extra column to your users table, name it logins. Whenever the user logs in increment the column by 1, and in you login script u can check if the number of logins is equal to the limit and when the user logs out then you decrease the no of logins by
1 . A problem that might arise using this method is that if the user doesn’t log out and the server does not recognize the sessionn again the login is not decremented. To avoid this a better way of doing it is below. 1. Create a column name it logins and give it a data type of varchar(500) or preferably text because it might be difficult to predict the size of data we are expecting.
2. when the user logs in, check if the logins column is empty, if it is empty, create a json that contains the session_id, time of login using the time() function.
if($column_login == '' or count(json_decode($column_login)) == 0){
$login_json = json_encode([
['session_key'=>'session_key_generated', 'time' => time()]
]);
//then update the logins table with the above
}
3. If the logins column is not empty or the count of the column when decoded is greater than zero, then you check if the count is greater than login limit , if the number of logins is not yet greater than the login limit, then append the new session to the logins column in the database table
if(count(json_decode($column_login)) > 0 and count(json_decode($column_login)) < $login_limit){
$login_json = json_decode($column_login);
$login_json[] = ['session_key'=>'session_key_generated', 'time' => time()];
$login_json = json_encode($column_login);
//update the logins column with the new $login_json and log the user in
}
if(count(json_decode($column_login)) >= $limit){
$logins = json_decode($column_login);
foreach($logins as $key => $login){
if($login['time'] < time()-300){
//this checks if the iterated login is greater than the current time -300seconds and if found to be true then the user is inactive
//then set this current login to null by using the below statement
$logins[$key] = null; // or unset($logins[$key]) either should work;
}
}
//after iteration we check if the count of logins is still greater than the limit
if(count($logins) >= login_limit){
//then return a login error that maximum logins reached
}else{
//then login is successsfull
}
//update the logins column to equal to json_encode($logins);
}
5. In any request that is been made by a logged user you check if the session key still exists in the login column of the database ($logins[‘session_key’]), and if it is not found then log the user out immediately to avoid escalation of right and if otherwise then update the $login[‘time’] to the new time().This method works well.
It is nice post and I found some interesting information on this blog, keep it up. Thanks for sharing. . .
ReplyDeletePHP Database Programming in India