Php: How to Detect If a Session Has Expired Automatically

Expire session automatically and detect if the session has expired in Codeigniter

you can store data in session object and user redirect any page , you can check session object already exist if not exist you can show alert, session is expired

Check if Codeigniter session has expired with AJAX

You can do it like this

$.ajax({
type : 'POST',
url : '<?php echo site_url('controllername/methodname')?>'
success : function(data){
if(data){
//session available
}else{
// expired
}
});

And controller method

 function methodname(){
$user_id = $this->session->userdata('user_id');
if($user_id){
echo 1;
}else{
echo 0;
}
}

You can wrap ajax request in function and return the result everytime with TRUE or FALSE. Moreover setInterval can call this function for checking session.

How to detect if session is about to expire?

Solution:

As soon as the client logs in they receive the session expiration date from the server. Then I set up a timer on client side, which after being idle for X (10 in my case) minutes, calls the API in every minute and checks if the session is still alive and if there is more time left than two minutes. If only two minutes left, I raise a warning message on the client side to inform the user that their session is about to expire (I also used this event to fire the auto save functions).

How to check session expired when user is idle codeigniter


This can be done with combination of jQuery/javascript/Ajax and a Codeigniter function.

JS

<script type="text/javascript">
var currentSessionValue = 1;
// pseudo code
setTimeout(checkSession, 5000);
function checkSession() {
$.ajax({
url: "CheckSession/check_session", //Change this URL as per your settings
success: function(newVal) {
if (newVal != currentSessionValue);
currentSessionValue = newVal;
alert('Session expired.');
window.location = 'Your redirect login URL goes here.';
}
});
}
</script>

Codeigniter

class CheckSession extends Controller{
public function __construct(){
session_start();
}
public function check_session(){
//Below last_visited should be updated everytime a page is accessed.
$lastVisitTime = $this->session->userdata("last_visited");
$fiveMinutesBefore = date("YmdHi", "-5 minutes");

echo date("YmdHi", strtotime($lastVisitTime)) > $fiveMinutesBefore > 1 : 0;
}
}

How do I expire a PHP session after 30 minutes?

You should implement a session timeout of your own. Both options mentioned by others (session.gc_maxlifetime and session.cookie_lifetime) are not reliable. I'll explain the reasons for that.

First:

session.gc_maxlifetime

session.gc_maxlifetime specifies the number of seconds after which data will be seen as 'garbage' and cleaned up. Garbage collection occurs during session start.

But the garbage collector is only started with a probability of session.gc_probability divided by session.gc_divisor. And using the default values for those options (1 and 100 respectively), the chance is only at 1%.

Well, you could simply adjust these values so that the garbage collector is started more often. But when the garbage collector is started, it will check the validity for every registered session. And that is cost-intensive.

Furthermore, when using PHP's default session.save_handler files, the session data is stored in files in a path specified in session.save_path. With that session handler, the age of the session data is calculated on the file's last modification date and not the last access date:

Note: If you are using the default file-based session handler, your filesystem must keep track of access times (atime). Windows FAT does not so you will have to come up with another way to handle garbage collecting your session if you are stuck with a FAT filesystem or any other filesystem where atime tracking is not available. Since PHP 4.2.3 it has used mtime (modified date) instead of atime. So, you won't have problems with filesystems where atime tracking is not available.

So it additionally might occur that a session data file is deleted while the session itself is still considered as valid because the session data was not updated recently.

And second:

session.cookie_lifetime

session.cookie_lifetime specifies the lifetime of the cookie in seconds which is sent to the browser. […]

Yes, that's right. This only affects the cookie lifetime and the session itself may still be valid. But it's the server's task to invalidate a session, not the client. So this doesn't help anything. In fact, having session.cookie_lifetime set to 0 would make the session’s cookie a real session cookie that is only valid until the browser is closed.

Conclusion / best solution:

The best solution is to implement a session timeout of your own. Use a simple time stamp that denotes the time of the last activity (i.e. request) and update it with every request:

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

Updating the session data with every request also changes the session file's modification date so that the session is not removed by the garbage collector prematurely.

You can also use an additional time stamp to regenerate the session ID periodically to avoid attacks on sessions like session fixation:

if (!isset($_SESSION['CREATED'])) {
$_SESSION['CREATED'] = time();
} else if (time() - $_SESSION['CREATED'] > 1800) {
// session started more than 30 minutes ago
session_regenerate_id(true); // change session ID for the current session and invalidate old session ID
$_SESSION['CREATED'] = time(); // update creation time
}

Notes:

  • session.gc_maxlifetime should be at least equal to the lifetime of this custom expiration handler (1800 in this example);
  • if you want to expire the session after 30 minutes of activity instead of after 30 minutes since start, you'll also need to use setcookie with an expire of time()+60*30 to keep the session cookie active.

Find out if a session with a particular id has expired

You can't just rely on session.gc_maxlifetime because after this time the session is marked as garbage and the garbage collector starts only with a probability of 1% by default ( session.gc_probability).

The better approach IMHO is to handle yourserlf the expired data.

You can for instance start the time and save it into a session variable:

<?php $_SESSION['last_seen'] = time();//Update this value on each user interaction. ?>

Later..via cron you can do something like this:

<?php
//Get the session id from file name and store it into the $sid variable;
session_id($sid);//try to resume the old session
session_start();
if (isset($_SESSION['last_seen']) && $_SESSION['last_seen'] > $timeout){//Session is expired
//delete file
session_destroy();
}else if (!isset($_SESSION['last_seen')){ //already garbaged
//delete file
session_destroy();
}
?>

Not tested...just an idea



Related Topics



Leave a reply



Submit