如何在PHP中设置会话超时代码

时间:2013-11-27 06:57:17

标签: php session

我有一页session.php,我的代码是:

 @session_start();
            if(!isset($_SESSION['uname']) || $_SESSION['uname'] == " " || !isset($_SESSION['uid']) || $_SESSION['uid'] == " ")
                   {
                echo "<script language='javascript'>";
                echo "window.location='../index.php'";
                echo "</script> ";
                exit;           
            }

我还想编辑会话超时功能,这段代码是:

$_SESSION['start'] = time(); // taking now logged in time
        $_SESSION['expire'] = $_SESSION['start'] + (1* 10) ; // ending a session in 30 seconds
            $now = time(); // checking the time now when home page starts
            if($now > $_SESSION['expire'])
            {
                session_destroy();
                echo "Your session has expire !  <a href='logout.php'>Click Here to Login</a>";
            }
            else
            {
                echo "This should be expired in 1 min <a href='logout.php'>Click Here to Login</a>";
            }

但是这段代码没有用,请帮助我如何在session.php页面中设置会话超时。

谢谢..

1 个答案:

答案 0 :(得分:0)

你可以试试这个,因为在你的代码中,你设置了每个时间和时间。每次页面加载时,现在都添加了条件。

    @session_start();       
    if(!isset($_SESSION['uname']) || $_SESSION['uname'] == " " || !isset($_SESSION['uid']) || $_SESSION['uid'] == " ")
    {
        echo "<script language='javascript'>";
        echo "window.location='../index.php'";
        echo "</script> ";
        exit;
    }

    $_SESSION['start'] = time(); // taking now logged in time

    if(!isset($_SESSION['expire'])){
        $_SESSION['expire'] = $_SESSION['start'] + (1* 10) ; // ending a session in 30 seconds
    }
    $now = time(); // checking the time now when home page starts

    if($now > $_SESSION['expire'])
    {
        session_destroy();
        echo "Your session has expire !  <a href='logout.php'>Click Here to Login</a>";
    }
    else
    {
        echo "This should be expired in 1 min <a href='logout.php'>Click Here to Login</a>";
    }