Automatic Logout After 15 Minutes of Inactive in PHP

Automatic Logout after 15 minutes of inactive in php

This is relatively easy to achive with this small snippet here:

 if(time() - $_SESSION['timestamp'] > 900) { //subtract new timestamp from the old one
echo"<script>alert('15 Minutes over!');</script>";
unset($_SESSION['username'], $_SESSION['password'], $_SESSION['timestamp']);
$_SESSION['logged_in'] = false;
header("Location: " . index.php); //redirect to index.php
exit;
} else {
$_SESSION['timestamp'] = time(); //set new timestamp
}

how to make user logout after 30 mins of inactivity?

I think this may help : How do I expire a PHP session after 30 minutes?

if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 1800)) {
// last request was more than 30 minutes ago
session_unset(); // unset $_SESSION variable for the run-time
session_destroy(); // destroy session data in storage
}
$_SESSION['LAST_ACTIVITY'] = time(); // update last activity time stamp

User Inactivity Logout PHP

You could also do:

$_SESSION['loginTime'] = time();

On every page, and when the user is trying to navigate and he has been inactive for an twenty minutes you can log him out like this:

if($_SESSION['loginTime'] < time()+20*60){ logout(); }

how to auto log out if user is inactive for some specific duration using codeigniter

// Add the following into your HEAD section
var timer = 0;
function set_interval() {
// the interval 'timer' is set as soon as the page loads
timer = setInterval("auto_logout()", 10000);
// the figure '10000' above indicates how many milliseconds the timer be set to.
// Eg: to set it to 5 mins, calculate 5min = 5x60 = 300 sec = 300,000 millisec.
// So set it to 300000
}

function reset_interval() {
//resets the timer. The timer is reset on each of the below events:
// 1. mousemove 2. mouseclick 3. key press 4. scroliing
//first step: clear the existing timer

if (timer != 0) {
clearInterval(timer);
timer = 0;
// second step: implement the timer again
timer = setInterval("auto_logout()", 10000);
// completed the reset of the timer
}
}

function auto_logout() {
// this function will redirect the user to the logout script
window.location = "your_logout_script.php";
}

// Add the following attributes into your BODY tag
onload="set_interval()"
onmousemove="reset_interval()"
onclick="reset_interval()"
onkeypress="reset_interval()"
onscroll="reset_interval()"

PHP automatic logout without having to refresh the page

I guess the best way to implement is by using the combination of JS and PHP

check.php

if(isset($_SESSION['timeout']) ) {
$session_life = time() - $_SESSION['timeout'];
if($session_life > $inactive) echo "0";

else echo "1";
}

$_SESSION['timeout'] = time();

.js

$(document).ready(function(){
setTimeout(function(){
$.get("check.php", function(data){
if(data==0) window.location.href="logout.php";
});
},1*60*1000);
});

Or just wrap it in setInterval(function(){},1*60*1000) instead of setTimeout() if you want it to be checked after every one minute.

$(document).ready(function(){
setInterval(function(){
$.get("check.php", function(data){
if(data==0) window.location.href="logout.php";
});
},1*60*1000);
});

How to logout after X minutes of inactivity on button click?

In summary, your issue is caused by the redirect occurring in save.php when it is being requested by ajax.

What happens is the redirect() request is processed transparently and the results are being processed by the jQuery.ajax().done() closure, which is trying to call JSON.parse(response); for the HTML of login.php.
You should be able to validate this by viewing the developer tools (usually F12) in your browser, when clicking the button.

The general approach to resolve the issue, is to determine if the request is a XMLHttpRequest and send a different response instead of redirecting.

Detect XMLHttpRequest

To determine if the request is coming from jQuery.ajax(), you would check the X-Requested-With request header.

isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest'

JSON Response with redirect property

This approach returns a redirect property in the response and uses it to redirect from the jQuery.ajax().done() closure.

helpers.php

if (! function_exists('redirect')) {
function redirect(string $url, int $status_code = 303): void
{
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
//do not redirect AJAX requests
echo json_encode(['redirect' => $url]);
} else {
header('Location: ' . $url, true, $status_code);
}
die();
}
}

index.php

$(function() {
"use strict";
$('form').submit(function(e) {
e.preventDefault();
$.post({
url: 'save.php',
data: $(this).serialize(),
}).done(response => {
response = JSON.parse(response);
if (response.redirect) {
//redirect user
window.location.href = response.redirect;
}
if (response.message) {
alert(response.message);
}
});
});
});

Status Code Response

This approach returns a status code other than 200 Ok, instead of redirecting and checks for the response status code in the jQuery.ajax() or statusCode: method(s).

helpers.php

if (! function_exists('redirect')) {
function redirect(string $url, int $status_code = 303): void
{
if (isset($_SERVER['HTTP_X_REQUESTED_WITH']) && strtolower($_SERVER['HTTP_X_REQUESTED_WITH']) === 'xmlhttprequest') {
//do not redirect AJAX requests
http_response_code(401); //Unauthorized - PHP 5.4+
echo $url; //optionally output the url
} else {
header('Location: ' . $url, true, $status_code);
}
die();
}
}

Here you can choose to handle the status code as desired.
For the simplest approach, checking the fail() jqXhr object status code and perform a javascript redirect instead.

index.php

$(function() {
"use strict";
$('form').submit(function(e) {
e.preventDefault();
$.post({
url: 'save.php',
data: $(this).serialize(),
}).done(response => {
response = JSON.parse(response);
if (response.message) {
alert(response.message);
}
}).fail(jqXhr => {
if (jqXhr.status == 401) {
//redirect to specified url in the response text
window.location.href = jqXhr.responseText;
/* alternatively hard-code '/logout.php' */
}
});
});
});


Related Topics



Leave a reply



Submit