how to expire php session if user is inactive for 15 mins

49,175

Solution 1

Call below function in your header file, so that whenever user does any activity at that time page gets refreshed and check whether session time outs or not.

function auto_logout($field)
{
    $t = time();
    $t0 = $_SESSION[$field];
    $diff = $t - $t0;
    if ($diff > 1500 || !isset($t0))
    {          
        return true;
    }
    else
    {
        $_SESSION[$field] = time();
    }
}

Use something like this in header

    if(auto_logout("user_time"))
    {
        session_unset();
        session_destroy();
        location("login.php");          
        exit;
    }       

User_time is the session name. I hope this answer will help you. What actually this code does is : "Checks whether diff is greater than 1500 seconds or not. If not then set new session time." You can change time diff(1500) according to your requirement.

Solution 2

try

  ini_set('session.gc_maxlifetime',54000);  
  ini_set('session.gc_probability',1);
  ini_set('session.gc_divisor',1); 

use this before calling session_start()

Solution 3

Store time() in the $time variable. create variable called $setTime and set the time you want user to timeout.

After that check the condition that if $_SESSION['setTime'] is empty OR not set then store the timeout value into the session, otherwise when the page will refresh the new value will be assigned to the $_SESSION['setTime'].

$time = time ();
    $setTime = time () + 60;
    if (empty ( $_SESSION ['setTime'] ) || !isset ( $_SESSION ['setTime'] )) {
        $_SESSION ['setTime'] = $setTime;
    }

After that check that current time is more than equal to the stored time. and if it is unset the session. destroy the session as well.

if (time () >= ( int ) $_SESSION ['setTime']) {
   session_unset ();
   session_destroy ();
}

Solution 4

I know this is an answered question but I just wanted to share my experience and since I feel like this is a more easy approach. I'm not sure if this is the best way but here goes. What I did was:

  1. I set a PHP Session ($_SESSION['timeout']) to current time (time()) when the user logged in.

  2. Wrote the following function to validate whether the user is active.

function sessionTimeOut() {

// This function is adding 900 seconds (15 Minutes, which is the amount of time you want the user to // be inactive to automatically logout) to the previously registered time when the user was last active. // Then, its checking whether the current time is greater than the amount of time you want the user to // stay logged in without timing out (which is 15 minutes). If it's greater, then you are redirected to the // login page where you can initiate a logout function with http://www.yourwebpage/login.php?status=timeout on the URL.

if ($_SESSION['timeout'] + 900 > time()) {

  // User Active so reset time session.
  $_SESSION['timeout'] = time();

} else {

  // session timed out then redirect to login page
  header('Location:http://'. $_SERVER[HTTP_HOST] . '/login.php?status=timeout');

}

}

Lastly: Call sessionTimeOut(); function in the header after checking if user is logged in. This allows the function to be called every time the user refreshes or navigates to a new page. Thus, it works perfectly (atleast in my case), fulfils my purpose, so I thought I'd just share it with you guys.

Solution 5

You can use something like this

# Session Logout after in activity 
function sessionX(){ 
    $logLength = 1800; # time in seconds :: 1800 = 30 minutes 
    $ctime = strtotime("now"); # Create a time from a string 
    # If no session time is created, create one 
    if(!isset($_SESSION['sessionX'])){  
        # create session time 
        $_SESSION['sessionX'] = $ctime;  
    }else{ 
        # Check if they have exceded the time limit of inactivity 
        if(((strtotime("now") - $_SESSION['sessionX']) > $logLength) && isLogged()){ 
            # If exceded the time, log the user out 
            logOut(); 
            # Redirect to login page to log back in 
            header("Location: /login.php"); 
            exit; 
        }else{ 
            # If they have not exceded the time limit of inactivity, keep them logged in 
            $_SESSION['sessionX'] = $ctime; 
        } 
    } 
} 

But remember Function sessionX() MUST come after session_start()

See details here

Share:
49,175

Related videos on Youtube

mack
Author by

mack

Updated on July 09, 2022

Comments

  • mack
    mack over 1 year

    i have created one project in PHP, into which i am managing sessions.

    I am creating session in my config.php file by writing following line of code.

    session_start();
    

    and to destroy this session, in logout.php file i have write following line.

    session_destroy();
    

    and i have not mention any code for session in any other project file, but the problem is session is active untill i call logout.php,

    what i want is session should expire if user is inactive for 15 minutes.

    can anyone help me for this, i am new to PHP, please give some example code or link to achieve this..

  • mack
    mack almost 12 years
    if i write this code in my config.php file only, will this work for entire project, as my config.php is included in all other project files ??
  • mack
    mack almost 12 years
    if i write this 3 lines in my config.php file before session_start() will it work for my entire project? as config.php is included in all other project files
  • mack
    mack almost 12 years
    ok, following is the code in my config.php see will it work? <?php ini_set('session.gc_maxlifetime',54000); ini_set('session.gc_probability',1); ini_set('session.gc_divisor',1); session_start(); $link = mysql_connect('localhost','root'); mysql_select_db('dbname',$link) or die("Not Able To Connect To DataBase"); ?>
  • mack
    mack almost 12 years
    i have write following code in config.php for testing purpose <?php ini_set('session.gc_maxlifetime',3600); ini_set('session.gc_probability',1); ini_set('session.gc_divisor',1); session_start(); $link = mysql_connect('localhost','root'); mysql_select_db('dbname',$link) or die("Not Able To Connect To DataBase"); ?> which means session should expire in 1 min, but i didn't
  • mack
    mack almost 12 years
    just one question kamal, how do i create a session with name user_time, becoz i used to simply write session_start()
  • Kamal Joshi
    Kamal Joshi almost 12 years
    You need to write $_SESSION['name'];
  • cssyphus
    cssyphus about 8 years
    I also tried this solution -- didn't work for me either.