gowri
gowri

Reputation: 3103

Automatic session timeout

I need to set, automatic session time out after some fixed time in my site.

I used the script below but it's not working properly.

I set the some time but it automatically times out before that time.

if((empty($Session_UserId)) || (empty($Session_Username)))
    header("Location:index.php");

if($_SESSION['session_count'] == 0) {
$_SESSION['session_count'] = 1;
$_SESSION['session_start_time']=time();
} else {
$_SESSION['session_count'] = $_SESSION['session_count'] + 1;
}

$session_timeout = $logout_sec; // 30 minute (in sec)

 $session_duration = time() - $_SESSION['session_start_time'];
if ($session_duration > $session_timeout) {
session_unset();
session_destroy();
session_start();
session_regenerate_id(true);
$_SESSION["expired"] = "yes";
header("Location:index.php"); // Redirect to Login Page
} else {
$_SESSION['session_start_time']=time();
} 

Upvotes: 0

Views: 2160

Answers (2)

Philbert McPleb
Philbert McPleb

Reputation: 325

I think what people are trying to say is, try the code below. which is a copy/paste of your code just without the last else statement.

if((empty($Session_UserId)) || (empty($Session_Username)))
header("Location:index.php");

if($_SESSION['session_count'] == 0) {
$_SESSION['session_count'] = 1;
$_SESSION['session_start_time']=time();
} else {
$_SESSION['session_count'] = $_SESSION['session_count'] + 1;
}

$session_timeout = $logout_sec; // 30 minute (in sec)

 $session_duration = time() - $_SESSION['session_start_time'];
if ($session_duration > $session_timeout) {
session_unset();
session_destroy();
session_start();
session_regenerate_id(true);
$_SESSION["expired"] = "yes";
header("Location:index.php"); // Redirect to Login Page
}

Upvotes: 1

Gumbo
Gumbo

Reputation: 655189

The problem with your code is the last if/else construct. Because if the session has not been timed out, the session start time is set to the current time. So this is rather a “last activity” time stamp. If you drop the else block, the session will not be usable longer than your time out.

Upvotes: 0

Related Questions