At this point i am interested to see other techniques on handling session timeouts.
What are some good improvements on this script to detect when a session is no longer valid?
Important definitions:
session.gc_maxlifetime - (default 1440 seconds) defines how long an unused PHP session will be kept alive. For example: A user logs in, browses through your application or web site, for hours, for days. No problem. As long as the time between his clicks never exceed 1440 seconds. It's a timeout value.
session.cookie_lifetime - *This value (default 0, which means until the browser's next restart) defines how long (in seconds) a session cookie will live. Sounds similar to session.gc_maxlifetime, but it's a completely different approach. This value indirectly defines the "absolute" maximum lifetime of a session, whether the user is active or not. If this value is set to 1*60*60, every session ends after an hour.*
Problems to address:
- Session timeout
- Cookie timeout
- Browser deleted cookies / cleared history
SESSION_handler.php
<?php
class SESSION_handler{
public static $gc_maxlifetime;
public static $cookie_lifetime;
function __construct(){
self::$gc_maxlifetime = ini_get('session.gc_maxlifetime');
self::$cookie_lifetime = ini_get('session.cookie_lifetime');
if(session_status() == PHP_SESSION_NONE) {
session_start();
}
}
public function get($session_key){
if(session_status() == PHP_SESSION_NONE) {
if(!empty($_SESSION[$session_key])){
$_SESSION['time_at_last_session'] = time();
return $_SESSION[$session_key];
}
}
return undefined;
}
public function set($session_key, $session_value){
if(session_status() == PHP_SESSION_NONE) {
$_SESSION[$session_key] = $session_value;
$_SESSION['time_at_last_session'] = time();
return $_SESSION[$session_key];
}
return undefined;
}
public function session_expired(){
if(
time() - ((!empty($_SESSION['time_at_last_session']))? $_SESSION['time_at_last_session'] : 0) >= self::$gc_maxlifetime ||
session_status() == PHP_SESSION_NONE ||
!isset($_COOKIE[session_name()])
){
return true;
}
return false;
}
}
?>
is_session_expired.php
<?php
$SESSION = new SESSION_handler();
if($SESSION->session_expired()){
echo "true";
}else{
echo "false";
}
?>
AJAX
<script type="text/javascript">
$(document).ready(function(){
(function(){
tmp_ = arguments.callee;
window.setTimeout(function(){
$.ajax({
url:'/php/is_session_expired.php',
success: function(session_expired){
if(session_expired == "true"){
alert("session has expired");
}else{
console.log('session has not expired');
}
}
});
});
})();
})
</script>
$this->time_at_last_session
initialized? I do not see where? \$\endgroup\$