如果用户在15分钟内处于非活动状态,如何终止php会话 [英] how to expire php session if user is inactive for 15 mins

查看:69
本文介绍了如果用户在15分钟内处于非活动状态,如何终止php会话的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经用PHP创建了一个项目,我正在其中管理会话.

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

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

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

session_start();

为了销毁此会话,在logout.php文件中,我写了下一行.

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

session_destroy();

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

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,

如果用户不活动15分钟,会话应该过期.

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

有人可以帮我吗,我是PHP的新手,请提供一些示例代码或链接来实现这一目标.

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

推荐答案

在头文件中调用以下函数,以便每当用户在该时间进行任何活动时,页面都会刷新,并检查会话是否超时.

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是会话名称.希望这个答案对您有帮助.该代码的实际作用是:检查差异是否大于1500秒.如果不是,则设置新的会话时间."您可以根据需要更改时间diff(1500).

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.

这篇关于如果用户在15分钟内处于非活动状态,如何终止php会话的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆