Limit session user PHP - javascript

How can I forbid a user from logging in with the same account in two different browsers at the same time.
session_start();
// set time-out period (in seconds)
$inactive = 30;
if( is_user_logged_in() ) {
if (isset($_SESSION["timeout"])) {
// calculate the session's "time to live"
$sessionTTL = time() - $_SESSION["timeout"];
if ($sessionTTL > $inactive) {
session_destroy();
$redirect_to = isset($_REQUEST['redirect_to']) ? $_REQUEST['redirect_to'] : '/wordpress';
$location = str_replace('&', '&', wp_logout_url($redirect_to));;
header("Location: $location");
}
else{
wp_die('<h1>User is login! </h1>', '', array( 'back_link' => true ));
}
}
}

For this you need to Create a one more table for login logs , in that these will be fields
userID islogin (default=0) logintime useragent
if user is login each time update that login time.
and if user is try to login then we need to check in that if user islogin =1 and logintime < session time . then die;
You need do that in wordpress i thing
so you need to add code filter for login function.
and on on init update the logintime
Thanks

Related

db table not getting updated when forcing logout using ajax

As stated in the title, db table trace_users is not getting updated when no activity happens for 30 mins but its get updated when its 6 mins.
The following code (both JS and PHP) is inside the same php file mno.php.
I am storing the last activity of user through this line let lastActivity = <?php echo time(); ?> ; present in the script below.
<?php
session_start();
if (isset($_GET['action']) && $_GET['action'] == "logout")
{
session_destroy(); // destroy session data in storage
!isset($_SESSION['admin']);
$open = "false";
$write = "0";
$stmt = $connect->prepare("UPDATE trace_users SET open=?, write=? WHERE user_name=?");
$usname = !empty($_SESSION['user_name']) ? $_SESSION['user_name'] : '';
$stmt->bind_param('sss', $open, $write, $usname);
$stmt->execute();
}
?>
<script>
jQuery(document).ready(function($) {
let lastActivity = <?php echo time(); ?> ; // storing last activity of user
let now = <?php echo time(); ?> ;
let logoutAfter = 360;
let timer = setInterval(function() {
now++;
let delta = now - lastActivity;
console.log(delta);
if (delta > logoutAfter) {
clearInterval(timer);
//DO AJAX REQUEST TO close.php
$.ajax({
url: "/abc/mno.php",
type: 'GET',
data: {
action: 'logout'
}, // Line A
success: function(data) {
console.log(data); // Line B
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
}
}, 1000);
});
</script>
Problem Statement:
I am wondering what changes I should make in the code above so that when no activity happens for 30 mins (1800 seconds) then the db table should also get updated.
Case1 (Not Working) : 1800 seconds (page logs out, db doesn't update)
Case2 (Working) : 360 seconds (page logs out, db gets updated)
The values inside session.gc_maxlifetime are 1440(Local Value) 1440(Master Value)
This is what I have tried/debugged:
On the network tab, I am getting Request Method GET when session timeout is set 6 mins and 60 mins.
You need to pass to the javascript some sort of permanent UID that identifies the user even after the session expires.
For the sake of simplification, I'm using user_name that already exists in your code. But you can also assign an UUID for each user, so that one can't guess another user's name and can't modify their stats.
First, you'll pass the $_SESSION['user_name'] from PHP to the JS closure.
let userName = "<?php echo $_SESSION['user_name']; ?>"; // don't forget to wrap the JS string value in quotes or apostrophes
Then, you'll pass it in the AJAX request payload.
data: {
action: 'logout',
user_name: userName // added param
},
Finally, you'll overwrite the value that is sent to DB (if it's sent with the payload)
$usname = !empty($_SESSION['user_name']) ? $_SESSION['user_name'] : ''; // original line
if (isset($_GET['user_name']) && !empty($_GET['user_name'])) {
$usname = $_GET['user_name'];
}
$stmt->bind_param('sss', $open, $write, $usname); // original line
Complete updated code:
<?php
if (isset($_GET['action']) && $_GET['action'] == "logout")
{
session_destroy(); // destroy session data in storage
!isset($_SESSION['pageadmin']);
$open = "false";
$write = "0";
$stmt = $connect->prepare("UPDATE trace_users SET open=?, write=? WHERE user_name=?");
$usname = !empty($_SESSION['user_name']) ? $_SESSION['user_name'] : '';
if (isset($_GET['user_name']) && !empty($_GET['user_name'])) {
$usname = $_GET['user_name'];
}
$stmt->bind_param('sss', $open, $write, $usname);
$stmt->execute();
}
?>
<script>
jQuery(document).ready(function($) {
let lastActivity = <?php echo time(); ?> ; // storing last activity of user
let now = <?php echo time(); ?> ;
let logoutAfter = 10;
let userName = "<?php echo $_SESSION['user_name']; ?>";
let timer = setInterval(function() {
now++;
let delta = now - lastActivity;
console.log(delta);
if (delta > logoutAfter) {
clearInterval(timer);
//DO AJAX REQUEST TO close.php
$.ajax({
url: "/abc/mno.php",
type: 'GET',
data: {
action: 'logout',
user_name: userName
}, // Line A
success: function(data) {
console.log(data); // Line B
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
}
}, 1000);
});
</script>
Few notes at the end:
It's bad practice to combine PHP, HTML and JS altogether in one file.
There are some parts of your code that are not easily reproducible and I had to guess from the context (e.g. i guessed that the session is already set, jQuery is used but there's no <script src="...jquery.js">, there's a DB query but no separate SQL import to try it quickly). Please read and apply the knowledge from How to create a Minimal, Reproducible Example in your next question, so that more people are able or willing to help you with it.
The problem is that you are not changing anything that will prevent the session from expiring after N seconds, you are just coding your script in a way that it will destroy the session after this time. The session gc (garbage colector) executes periodically and deletes old sessions and when that happens, $_SESSION['LAST_ACTIVITY'] will be deleted as well.
You must either try to prevent the gc from deleting sessions or change the logic in your application.
PHP process does not sit indefinitely and does not have program structure as a loop ala Node.js server, which won’t allow you to react to session expiry since it’s not a process that invalidates it, but rather a simple timestamp associated with session that is checked every time you attempt to work with it.
The solution I offer is a simple script that is ran every N minutes to perform a comparison of last user activity timestamp (which, I assume is updated on the request for that user) against expiry period (in you case it is 30 minutes). You can also set session expiry to 30 minutes, though strictly it’s not necessary. If the time difference will exceed 30 minutes, you update the timestamp for the user in your table, and invalidate their session if necessary. The script can be ran through cron or its alternatives and go through all users you require to perform a check.
Do not forget to handle the case when user is logged out on the server but client does not know about it and may continue sending logout requests - raising alert box is rather unclear (it is better to return HTTP Unauthorized code and handle it differently - redirecting to login screen, for example)
There are two things you need to fix.
1). Set the ajax request to be async:false.
$.ajax({
url: "/abc/mno.php",
type: 'GET',
async: false, // <---- ADDED ASYNC FALSE
data: {
action: 'logout'
}, // Line A
success: function(data) {
console.log(data); // Line B
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
2). Destroy the session after performing the SQL Query.
<?php
session_start();
if (isset($_GET['action']) && $_GET['action'] == "logout")
{
!isset($_SESSION['pageadmin']);
$open = "false";
$write = "0";
$stmt = $connect->prepare("UPDATE trace_users SET open=?, write=? WHERE user_name=?");
$usname = !empty($_SESSION['user_name']) ? $_SESSION['user_name'] : '';
$stmt->bind_param('sss', $open, $write, $usname);
$stmt->execute();
session_destroy(); // destroy session data in storage <---- DESTORY AT THE END
}
?>

update database table on session timeout in php

I have a php code as shown below in which session timeout happen after 60 mins when there is no activity. The following code is inside the file /mno.php. My login and logout code is also in the same file /mno.php.
/mno.php
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 3600)) {
session_destroy(); // destroy session data in storage
!isset($_SESSION['pageadmin']);
/* Update Table (START) */
$open="false";
$stmt= $connect->prepare("UPDATE trace_users SET open=? WHERE user_name=?");
$stmt->bind_param('ss', $open, $_SESSION['user_name']);
$stmt->execute();
/* Update Table (END) */
header('location: /mmo.php');
exit();
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
The table trace_users in the code keeps the track of all logged in users. In that table, there are two columns user_name and open. The value is set to true/false when any user log in/log out.
I have included sql query in which I am trying to update a table when there is no activity but unfortunately the column value is not getting set to false for that particular user when no activity happens for 60 mins.
This is what I have tried:
After doing some research, I think I have to run a timer (js/ajax). In the javascript shown below I have calculated the difference between the Last Activity and the Current time.
If its more than 60 mins, then it will update a db table. This is what I have tried but I believe more need to be done in order to update a table in db.
<script>
let x = setInterval(function() {
let lastActivity = <?php echo ($_SESSION['LAST_ACTIVITY']); ?>
let now = <?php echo time() ?>;
let difference = now - lastActivity;
if (difference > 3600) {
clearInterval(x);
}
}, 1000
);
</script>
Problem Statement:
I am wondering what changes I should make in the js (or php) code above so that when there is no activity for 60 mins, it should update the column open to false (in the table trace_users) for that particular user.
Edit 1:
My login code and session history code is in the same file /mno.php. I have placed everything in the same file /mno.php.
I think Vineys and jo0gbe4bstjbs answer is wrong because of when user close browser until 5 seconds, it can't update table after 60 mins and session too. Session deletes just after time in where set in php.ini configuration file.
And Do you mind requesting every 5 seconds is it good way to solve this? It is worst for performance.
If you want solve this problem with professionalism, you should add "last_request" column and delete "open" column from the table and after every request you should update last_requests value to current unix timestamp. And where getting users you should write:
$time = time() - 3600;
"SELECT * FROM `users` WHERE last_request > $time" //active users
"SELECT * FROM `users` WHERE last_request <= $time" //inactive users
And instead of ajax request every 5 seconds you should write setTimeout with 3600 second delay time which run window.location.href= '/mmo.php'; code.
Its way good if you want best performance and exactly result with 60 minute logout
I suppose you realize that this code
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 3600)) {
//...
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
runs on every request and only when a request arrives
Imagine I visit your website and then go out shopping keeping the browser open. What do you think will happen?
NOTHING - because there will be no new request sent to you (assuming you haven't implemented any periodic ajax polling / Websocket mechanism)
So the server won't bother about me until I come back from shopping and refresh the page, only then would the server realize "Hmmm..This guy's LAST_ACTIVITY is older than an hour let me update my trace_users table and set open as false for him"
Coming to your proposed solution, it looks good and avoids the complications of websockets/periodic ajax requests
Just need some minor corrections, follow here for a basic demo
<script>
var lastActivity = <?php echo ($_SESSION['LAST_ACTIVITY']); ?>; //the timestamp of latest page refresh or navigation
//This will remain constant as long as page stays put
var now = <?php echo time() ?>; //This takes inital value (technically same as LAST_ACTIVITY) from server
// but later on it will be incremented by javascript to act as counter
var logoutAfter = 5; //I set 5 sec for demo purposes
var timer = setInterval(function() {
now++;
let delta = now - lastActivity;
if ( delta > logoutAfter) {
alert('you are logged out');
clearInterval(timer);
//DO AJAX REQUEST TO close.php
}
}, 1000);
</script>
Here the lastActivity will hold the timestamp when the page was sent by server to browser it will be never changed by scripts on the browser,
now is your counter that you will use to track how much time passed since page was loaded on the browser, you'll increment it every second and check if a given amount of time has been crossed
If true do a ajax request (or simply redirect to logout.php) where you would destroy session and update the trace_users table to mark the user as closed
UPDATE
So ajax will be like
$.ajax({
url: "/close.php",
type: 'POST', // GET also fine
data: { },
success: function(data) {
window.location.href= '/mmo.php';
},
error: function(jqXHR, textStatus, errorThrown) {
alert(textStatus);
}
});
and
close.php
<?php
session_start();
$logoutAfter = 5; //5 sec timeout for testing purposes
// I'm not sure whether the below if condition check is required here or not
// because we have already checked (whether to timeout or not ) in our javascript
// and we call close.php only when it's affirmative
// I encourage you to test and find out :)
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > $logoutAfter)) {
session_destroy(); // destroy session data in storage
!isset($_SESSION['pageadmin']);
/* Update Table (START) */
$open="false";
$stmt= $connect->prepare("UPDATE trace_users SET open=? WHERE user_name=?");
$stmt->bind_param('ss', $open, $_SESSION['user_name']);
$stmt->execute();
/* Update Table (END) */
//header('location: /mmo.php'); //<-- no need of it when url hit by ajax
exit();
}
else //<-- note the else
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
Page.php
<!-- CODE TO INCLUDE IN HEADER.PHP -->
<?php
session_start();
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
?>
<!-- CLOSE -->
<html>
<head>
<script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.1.0/jquery.min.js"></script>
</head>
<body>
</body>
<script>
let lastActivity = <?php echo ($_SESSION['LAST_ACTIVITY']); ?>; //the timestamp of latest page refresh or navigation
//This will remain constant as long as page stays put
let now = <?php echo time() ?>; //This takes inital value (technically same as LAST_ACTIVITY) from server+
// but later on it will be incremented by javascript to act as counter
let logoutAfter = 5; //I set 5 secs for demo purposes
let timer = setInterval(function() {
now++;
let delta = now - lastActivity;
if ( delta > logoutAfter) {
alert('you are logged out');
clearInterval(timer);
//DO AJAX REQUEST TO close.php
$.ajax({
url: "/mmo.php",
type: 'POST', // GET also fine
data: { },
success: function(data) {
},
error: function(jqXHR, textStatus, errorThrown) {
console.log("I am inside error");
alert(textStatus);
}
});
}
}, 1000); //<-- you can increse it( till <= logoutAfter ) for better performance as suggested by #"Space Coding"
</script>
</html>
mmo.php
<?php
$servername = "localhost";
$username = "username";
$password = "password";
$dbname = "myDB";
$connect = new mysqli($servername, $username, $password, $dbname);
if ($connect->connect_error) {
die("Connection failed: " . $connect->connect_error);
}
session_start();
$logoutAfter = 5; //5 sec timeout for testing purposes
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > $logoutAfter)) {
session_destroy(); // destroy session data in storage
!isset($_SESSION['pageadmin']);
/* Update Table (START) */
$open="false";
$stmt= $connect->prepare("UPDATE trace_users SET open=? WHERE user_name=?");
$usname = !empty($_SESSION['user_name'])?$_SESSION['user_name']:'';
$stmt->bind_param('ss', $open, $usname );
$stmt->execute();
/* Update Table (END) */
//header('location: /mmo.php'); //<-- no need of it when url hit by ajax
exit();
}
else //<-- note the else
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp
?>
This is a simple time validation for web page:
$modified_on = isset($SERVER['HTTP_IF_MODIFIED_SINCE']) ? $SERVER['HTTP_IF_MODIFIED_SINCE'] : null;
$current_time = time();
if (!is_null($modified_on) && ($current_time - strtotime($modified_on)) > 3600) {
session_destroy();
...
}
header('Last-Modified: '.gmdate('D, d M Y H:i:s', $current_time).' GMT');
...

Show preloader once per visit

I have been trying to figure this out, I want to show preloader only once per visit. How can I do that?
Current code:
$(window).on('load', function() {
$('#status').fadeOut();
$('#preloader').delay(350).fadeOut('slow');
$('body').delay(350).css({'overflow':'visible'});
})
Could you try the sessionStorage
if ( ! sessionStorage.getItem( 'doNotShow' ) ) {
sessionStorage.setItem( 'doNotShow', true );
$('#preloader').delay(350).fadeOut('slow');
} else {
$('#preloader').hide();
}
Or take a look on this link How to show website preloader only once
No cookie whether session or persistent will provide a reliable solution to this problem. The only way I can see doing this properly would be to record the ip address of the visitor and check to see if that record matches one in a table:
If it doesn't, load the preloader.
If it does, don't load the preloader.
The only possible problem to this is people periodically clear the temp website data they collect so I would implement a timed record system and set it to a reasonable value like 30 days so if they haven't visited your site in 30 days we will presume they have cleared their cache and they will get the preloader, that would change the criteria to;
If visitor is new, load preloader
If visitor is old but less than 30 days, don't load preloader
If visitor is old and more than 30 days, delete record, create new record, load
preloader
Code example below;
#1: Detect IP
<?php
function myIp() {
$client = #$_SERVER['HTTP_CLIENT_IP'];
$forward = #$_SERVER['HTTP_X_FORWARDED_FOR'];
$remote = $_SERVER['REMOTE_ADDR'];
if(filter_var($client, FILTER_VALIDATE_IP))
{
$ip = $client;
}
elseif(filter_var($forward, FILTER_VALIDATE_IP))
{
$ip = $forward;
}
else
{
$ip = $remote;
}
return $ip;
}
$my_ip = myIp();
global $my_ip;
?>
#2: Operations
<?php
// Set preloader status
$play_preloader = "no";
// Check visitor ip records for current ip
$preloader_one = "select ip from preloader where ip='$my_ip'";
$connect_preloader_one = mysqli_query($con, $preloader_one);
$rows_preloader_one = mysqli_num_rows($connect_preloader_one);
// If no record exists, create a new one
if ($rows_preloader_one == 0) {
$preloader_insert = mysqli_prepare($con, "insert into preloader (ip) values (?)");
mysqli_stmt_bind_param($preloader_insert, "s", $my_ip);
mysqli_stmt_execute($preloader_insert);
$play_preloader = "yes";
// If records exist, find records older than 30 days
} else {
$preloader_two = "select ip,date from preloader where ip='$my_ip' and date < DATE_SUB(now(), INTERVAL 30 DAY)";
$connect_preloader_two = mysqli_query($con, $preloader_two);
// If records older than 30 days found
$rows_preloader_two = mysqli_num_rows($connect_preloader_two);
if ($rows_preloader_two > 0) {
// Delete old records
$preloader_delete = "delete from preloader where ip='$my_ip' and date < DATE_SUB(now(), INTERVAL 30 DAY)";
$preloader_delete_query = mysqli_query($con, $preloader_delete);
// Add new record
$preloader_insert = mysqli_prepare($con, "insert into preloader (ip) values (?)");
mysqli_stmt_bind_param($preloader_insert, "s", $my_ip);
mysqli_stmt_execute($preloader_insert);
$play_preloader = "yes";
// If records exist but no records are older than 1 month
} else {
$play_preloader = "no";
}
}
// Preloader
if ($play_preloader == "yes") {
$preloader = "
enter you html/js/css code for the preloader here
";
} else {
$preloader = "";
}
?>
Now save all the above code in a php file then reference it in your html and then call $preloader;
<html>
<head>
<?php include_once ('mypreloader.php'); ?>
</head>
<body>
<?php echo $preloader; ?>
</body>
</html>
This code has been tested on a running server and is working.

I was set values in session when user on first page when he click the back button session variables also set with i

this is my code how to use this code when user click back button
if(isset($_SESSION['Seats']))
{
$Eventid = $_SESSION['Eventid'];
$stmt = $con->prepare(
'UPDATE fistevent SET `Status`=" " where `Event_Id`=? AND `seats`=? AND `Status`="Hold" '
);
$stmt->bind_param(
"st",$_SESSION['Eventid'],
$_SESSION['Seats']
);
$stmt->execute();
session_destroy();
session_unset();
}
You need to check if the session has started first.
if(session_id() == '' || !isset($_SESSION)) {
session_start();
}
If not the start it.

Redirect losing POST/SESSION DATA

I have a problem with redirection, my whole code is working my only problem is losing a POST/SESSION data in the process. spent countless hours working with it and try alot of work arounds, but still it does not work and that is my only problem. here's my code
<?php
// First we execute our common code to connection to the database and start the session
require("common.php");
// This variable will be used to re-display the user's username to them in the
// login form if they fail to enter the correct password. It is initialized here
// to an empty value, which will be shown if the user has not submitted the form.
// This if statement checks to determine whether the login form has been submitted
// If it has, then the login code is run, otherwise the form is displayed
if(!empty($_POST)) {
// This query retreives the user's information from the database using
// their username.
if(isset($_POST['validEmail'])) {
$query = "SELECT *
FROM registered_email
WHERE email = :validEmail";
}
// The parameter values
$query_params = array( ':validEmail' => $_POST['validEmail'] );
try {
// Execute the query against the database
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex) {
// Note: On a production website, you should not output $ex->getMessage().
// It may provide an attacker with helpful information about your code.
die("Failed to run query");
}
// This variable tells us whether the user has successfully logged in or not.
// We initialize it to false, assuming they have not.
// If we determine that they have entered the right details, then we switch it to true.
$login_ok = false;
// Retrieve the user data from the database. If $row is false, then the username
// they entered is not registered.
$row = $stmt->fetch();
if($row) {
if($_POST['validEmail'] === $row['email']) {
// If they do, then we flip this to true
$login_ok = true;
}
}
// If the user logged in successfully, then we send them to the private members-only page
// Otherwise, we display a login failed message and show the login form again
if($login_ok) {
$_SESSION['sesEmail'] = $row;
// Redirect the user to the private members-only page.
if (isset($_POST['validEmail'])) {
echo "<script>location='http://www.url.com.ph/some.php'</script>";
}
} else {
// Tell the user they failed
print "Sorry to say that your Email is not Registered!.";
}
}
Ideally your code should look something like this, it should work fine as far as I see. I refactored your code and edited the redirect statement.
// I am assuming you have session_start(); included in common.php
require("common.php");
if(!empty($_POST)) {
if(isset($_POST['validEmail'])) {
$query = "SELECT *
FROM registered_email
WHERE email = :validEmail";
$query_params = array( ':validEmail' => $_POST['validEmail'] );
try {
$stmt = $db->prepare($query);
$result = $stmt->execute($query_params);
}
catch(PDOException $ex) {
die("Failed to run query");
}
$login_ok = false;
$row = $stmt->fetch();
if($row) {
if($_POST['validEmail'] === $row['email']) {
$login_ok = true;
}
}
if($login_ok) {
$_SESSION['sesEmail'] = $row;
if (isset($_POST['validEmail'])) {
// the page where you are redirecting should be linked with session as well
echo "<script>window.location.href='http://www.url.com.ph/some.php'</script>";
}
} else {
// Tell the user they failed
print "Sorry to say that your Email is not Registered!.";
}
}
else {
// Tell the user they failed
print "Sorry no POST parameters!.";
}
}
Hope it helps. If not feel free to discuss.

Categories

Resources