Php: Manage session times using code - Expiration / Timeout script - Code-Tips.com - Web Development, Programming, SEO

Tuesday, June 2, 2009

Php: Manage session times using code - Expiration / Timeout script

The following article demonstrates how to take control of php session times by including a php script into pages on your site.
This can be useful if you don't have access to the php installation and the php.ini configuration file, as it gives you the flexibility to choose the length of php sessions on your site without requiring access to the server or config.

Usage:

When a user is successfully logged into your site, store the time that the user logged in into a session variable $_SESSION['last_use'].

The following php script session_timer.php needs to be included on all pages of the site, or at least all pages that require the user to be logged in. The session_start() function is included at the top the session_timer.php script. This means that it is not required at the top of any page which includes session_timer.php.





session_start();
$maxSeconds = 600; //maximum session time in seconds

if (isset($_SESSION['user_id']) && isset($_SESSION['last_use']))
{
//Destroy if session older than maxSeconds (default 600 seconds)
if (($_SESSION['last_use']+$maxSeconds) < time())
{
//Session has expired: Destroy
session_destroy();

//Get the current request URI
$page = $_SERVER['REQUEST_URI'];

//Reload the current page in case it has been cached
Header ("Location: $page");
}
else
{
//Session still active and valid.
// - Update / Refresh session

$_SESSION['last_use'] = time();
}
}
else
{
//Required session variables not set. Destroy
session_destroy();
}



Each time the user requests a page on the site, the current time is checked against the last use time ($_SESSION['last_use']). If over 600 seconds (10 minutes) have passed, the session is destroyed and the page reloaded (in case it is cached). If less than 10 minutes have passed, the last use session variable is reset to the current time to keep the sssion going.

1 comment:

  1. That is nice informative post about to take control of php session times by including a php script.
    shopping cart

    ReplyDelete

Understood
This website is using cookies. More details