如果用户在15分钟内处于非活动状态,如何使php会话失效

时间:2022-04-21 01:17:37

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

我用PHP创建了一个项目,我正在管理会话。

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

我通过编写以下代码行在config.php文件中创建会话。

session_start();

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

并销毁此会话,在logout.php文件中我写了以下行。

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,

我没有在任何其他项目文件中提及任何会话代码,但问题是会话是活动的,直到我调用logout.php,

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

我想要的是如果用户15分钟不活动,会话应该到期。

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

任何人都可以帮助我,我是PHP的新手,请给出一些示例代码或链接来实现这一点..

6 个解决方案

#1


15  

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.

User_time是会话名称。我希望这个答案会对你有所帮助。实际上这段代码的作用是:“检查diff是否大于1500秒。如果没有,则设置新的会话时间。”您可以根据需要更改时间差异(1500)。

#2


4  

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()

在调用session_start()之前使用它

#3


2  

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

将时间()存储在$ time变量中。创建名为$ setTime的变量并设置希望用户超时的时间。

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'].

之后检查条件,如果$ _SESSION ['setTime']为空或未设置,则将超时值存储到会话中,否则当页面刷新时,新值将被分配给$ _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 ();
}

#4


1  

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()

但请记住函数sessionX()必须在session_start()之后

See details here

详情请见此处

#5


1  

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.

    当用户登录时,我将PHP会话($ _SESSION ['timeout'])设置为当前时间(time())。

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

    编写以下函数以验证用户是否处于活动状态。

function sessionTimeOut() {

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.

//此功能将900秒(15分钟,即您希望用户自动注销的时间自动注销)添加到用户上次活动时的先前注册时间。 //然后,它检查当前时间是否大于您希望用户//在没有超时(15分钟)的情况下保持登录的时间。如果它更大,那么您将被重定向到//登录页面,您可以在URL上启动http://www.yourwebpage/login.php?status = timeout的注销功能。

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

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

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

} else {

} 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.

最后:调用sessionTimeOut();检查用户是否登录后在标题中起作用。这允许每次用户刷新或导航到新页面时调用该函数。因此,它完美地工作(至少在我的情况下),实现我的目的,所以我想我会和你们分享。

#6


-1  

This is in continuation to what Kamal posted. I tried same code but made it work it by modifying it as below:

这是卡迈勒发布的内容的延续。我尝试了相同的代码但通过修改它使其工作如下:

/* code */
function fnlogout($field)
{
    $t = time();
    if (!isset($_SESSION[$field]))
        $_SESSION[$field] = time();
    $t0 = $_SESSION[$field];
    $diff = $t - $t0;
    if ($diff > 60)
    {        
        return true;
    }enter code here
    else
    {
        return false;
    }
}
function fnheader()
{
    if(fnlogout("user_time"))
    {
        session_unset();
        session_destroy();
        header("location:index.php?action=expired");
        exit;
    }
}

Yes, Kamal is right about the location of code inserts. One part as function and other in header of each file or common header function.

是的,Kamal对代码插入的位置是正确的。一部分作为函数,另一部分作为每个文件或公共头函数的标题。

#1


15  

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.

User_time是会话名称。我希望这个答案会对你有所帮助。实际上这段代码的作用是:“检查diff是否大于1500秒。如果没有,则设置新的会话时间。”您可以根据需要更改时间差异(1500)。

#2


4  

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()

在调用session_start()之前使用它

#3


2  

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

将时间()存储在$ time变量中。创建名为$ setTime的变量并设置希望用户超时的时间。

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'].

之后检查条件,如果$ _SESSION ['setTime']为空或未设置,则将超时值存储到会话中,否则当页面刷新时,新值将被分配给$ _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 ();
}

#4


1  

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()

但请记住函数sessionX()必须在session_start()之后

See details here

详情请见此处

#5


1  

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.

    当用户登录时,我将PHP会话($ _SESSION ['timeout'])设置为当前时间(time())。

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

    编写以下函数以验证用户是否处于活动状态。

function sessionTimeOut() {

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.

//此功能将900秒(15分钟,即您希望用户自动注销的时间自动注销)添加到用户上次活动时的先前注册时间。 //然后,它检查当前时间是否大于您希望用户//在没有超时(15分钟)的情况下保持登录的时间。如果它更大,那么您将被重定向到//登录页面,您可以在URL上启动http://www.yourwebpage/login.php?status = timeout的注销功能。

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

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

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

} else {

} 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.

最后:调用sessionTimeOut();检查用户是否登录后在标题中起作用。这允许每次用户刷新或导航到新页面时调用该函数。因此,它完美地工作(至少在我的情况下),实现我的目的,所以我想我会和你们分享。

#6


-1  

This is in continuation to what Kamal posted. I tried same code but made it work it by modifying it as below:

这是卡迈勒发布的内容的延续。我尝试了相同的代码但通过修改它使其工作如下:

/* code */
function fnlogout($field)
{
    $t = time();
    if (!isset($_SESSION[$field]))
        $_SESSION[$field] = time();
    $t0 = $_SESSION[$field];
    $diff = $t - $t0;
    if ($diff > 60)
    {        
        return true;
    }enter code here
    else
    {
        return false;
    }
}
function fnheader()
{
    if(fnlogout("user_time"))
    {
        session_unset();
        session_destroy();
        header("location:index.php?action=expired");
        exit;
    }
}

Yes, Kamal is right about the location of code inserts. One part as function and other in header of each file or common header function.

是的,Kamal对代码插入的位置是正确的。一部分作为函数,另一部分作为每个文件或公共头函数的标题。