Warning: file_get_contents(/data/phpspider/zhask/data//catemap/1/php/297.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
如何在30分钟后使PHP会话过期?_Php_Session_Cookies - Fatal编程技术网

如何在30分钟后使PHP会话过期?

如何在30分钟后使PHP会话过期?,php,session,cookies,Php,Session,Cookies,我需要让一个会话保持活动状态30分钟,然后销毁它 这是否用于在设定的时间后注销用户?在注册时设置会话创建时间(或到期时间),然后检查每个页面加载是否可以处理该时间 例如: 编辑:我觉得你是指其他东西 通过使用ini设置,您可以在特定的生命周期后废弃会话: 编辑: ini_集('session.gc_maxlife',60*30) 您应该实现自己的会话超时。其他人(和)提到的两个选项都不可靠。我会解释原因的 第一名: session.gc\u maxlifetime session.gc_maxl

我需要让一个会话保持活动状态30分钟,然后销毁它

这是否用于在设定的时间后注销用户?在注册时设置会话创建时间(或到期时间),然后检查每个页面加载是否可以处理该时间

例如:

编辑:我觉得你是指其他东西

通过使用ini设置,您可以在特定的生命周期后废弃会话:

编辑:
ini_集('session.gc_maxlife',60*30)

您应该实现自己的会话超时。其他人(和)提到的两个选项都不可靠。我会解释原因的

第一名:

session.gc\u maxlifetime
session.gc_maxlifetime指定数据被视为“垃圾”并被清除的秒数。垃圾回收在会话启动期间发生

但是垃圾收集器的启动概率仅为除以。使用这些选项的默认值(分别为1和100),概率仅为1%

您可以简单地调整这些值,以便更频繁地启动垃圾收集器。但是当垃圾收集器启动时,它将检查每个注册会话的有效性。这是成本密集型的

此外,当使用PHP的默认文件时,会话数据存储在中指定的路径中的文件中。使用该会话处理程序,会话数据的期限是根据文件的最后修改日期而不是最后访问日期计算的:

注意:如果使用默认的基于文件的会话处理程序,则文件系统必须跟踪访问时间(atime)。Windows FAT不是这样的,因此如果您使用的是FAT文件系统或任何其他无法使用atime跟踪的文件系统,那么您必须想出另一种方法来处理会话垃圾收集。自PHP4.2.3以来,它使用了mtime(修改日期)而不是atime。这样,您就不会在没有atime跟踪的文件系统中遇到问题

因此,由于会话数据最近未更新,因此在会话本身仍被视为有效时,会话数据文件可能会被删除

第二名:

会话。cookie\u生存期
session.cookie\u lifetime指定发送到浏览器的cookie的生存期(以秒为单位)。[……]

是的,没错。这只会影响cookie生存期,会话本身可能仍然有效。但是,使会话无效是服务器的任务,而不是客户端的任务。所以这没有任何帮助。事实上,将session.cookie_life设置为
0
将使会话的cookie成为一个真正的cookie,它只有在浏览器关闭之前才有效

结论/最佳解决方案:

最好的解决方案是实现自己的会话超时。使用简单的时间戳表示最后一个活动(即请求)的时间,并随每个请求更新:

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
使用每个请求更新会话数据也会更改会话文件的修改日期,以便垃圾收集器不会过早删除会话

您还可以使用额外的时间戳定期重新生成会话ID,以避免对会话的攻击,如:

注意事项:

  • session.gc_maxlifetime
    应至少等于此自定义过期处理程序的生存期(本例中为1800)
  • 如果要在活动30分钟后而不是启动后30分钟后使会话过期,还需要使用过期时间为
    time()+60*30
    setcookie
    ,以保持会话cookie处于活动状态
PHP会话在30分钟内到期的简单方法。 注意:如果您想更改时间,只需将30更改为您想要的时间,不要更改*60:这将给出分钟数


分钟:(30*60)
天数:(n*24*60*60)n=天数


Login.php

用户名
密码
HomePage.php

欢迎
LogOut.php
使用如下函数实际上很容易。它使用数据库表名“sessions”和字段“id”和“time”

每当用户再次访问您的站点或服务时,您应该调用此函数检查其返回值是否为TRUE。如果为FALSE,则用户已过期,会话将被销毁(注意:此函数使用数据库类来连接和查询数据库,当然您也可以在函数或类似的内容中执行此操作):

功能会话\u超时\u正常(){
全球$db;
$timeout=SESSION\u timeout;//常数,例如6*60,持续6分钟
$ok=false;
$session_id=session_id();
$sql=“从会话中选择时间,其中会话_id=””$session_id。“”;
$rows=$db->query($sql);
如果($rows==false){
//无法读取时间戳
$ok=FALSE;
}
否则{
//已成功读取时间戳
如果(计数($rows)>0){
$zeile=$rows[0];
$time_pass=$zeile['time'];
如果($timeout+$time\u过去query($sql);
$ok=FALSE;
}
否则{
//时间还行
$ok=TRUE;
$sql=“updatesessions SET time=”.time()。“'其中session_id=”。“$session_id.”;
if (isSet($_SESSION['started'])){
    if((mktime() - $_SESSION['started'] - 60*30) > 0){
        //Logout, destroy session, etc.
    }
}
else {
    $_SESSION['started'] = mktime();
}
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
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
}
<?php
    session_start();
?>

<html>
    <form name="form1" method="post">
        <table>
            <tr>
                <td>Username</td>
                <td><input type="text" name="text"></td>
            </tr>
            <tr>
                <td>Password</td>
                <td><input type="password" name="pwd"></td>
            </tr>
            <tr>
                <td><input type="submit" value="SignIn" name="submit"></td>
            </tr>
        </table>
    </form>
</html>

<?php
    if (isset($_POST['submit'])) {
        $v1 = "FirstUser";
        $v2 = "MyPassword";
        $v3 = $_POST['text'];
        $v4 = $_POST['pwd'];
        if ($v1 == $v3 && $v2 == $v4) {
            $_SESSION['luser'] = $v1;
            $_SESSION['start'] = time(); // Taking now logged in time.
            // Ending a session in 30 minutes from the starting time.
            $_SESSION['expire'] = $_SESSION['start'] + (30 * 60);
            header('Location: http://localhost/somefolder/homepage.php');
        } else {
            echo "Please enter the username or password again!";
        }
    }
?>
<?php
    session_start();

    if (!isset($_SESSION['luser'])) {
        echo "Please Login again";
        echo "<a href='http://localhost/somefolder/login.php'>Click Here to Login</a>";
    }
    else {
        $now = time(); // Checking the time now when home page starts.

        if ($now > $_SESSION['expire']) {
            session_destroy();
            echo "Your session has expired! <a href='http://localhost/somefolder/login.php'>Login here</a>";
        }
        else { //Starting this else one [else1]
?>
            <!-- From here all HTML coding can be done -->
            <html>
                Welcome
                <?php
                    echo $_SESSION['luser'];
                    echo "<a href='http://localhost/somefolder/logout.php'>Log out</a>";
                ?>
            </html>
<?php
        }
    }
?>
<?php
    session_start();
    session_destroy();
    header('Location: http://localhost/somefolder/login.php');
?>
function session_timeout_ok() {
    global $db;
    $timeout = SESSION_TIMEOUT; //const, e.g. 6 * 60 for 6 minutes
    $ok = false;
    $session_id = session_id();
    $sql = "SELECT time FROM sessions WHERE session_id = '".$session_id."'";
    $rows = $db->query($sql);
    if ($rows === false) {
        //Timestamp could not be read
        $ok = FALSE;
    }
    else {
        //Timestamp was read succesfully
        if (count($rows) > 0) {
            $zeile = $rows[0];
            $time_past = $zeile['time'];
            if ( $timeout + $time_past < time() ) {
                //Time has expired
                session_destroy();
                $sql = "DELETE FROM sessions WHERE session_id = '" . $session_id . "'";
                $affected = $db -> query($sql);
                $ok = FALSE;
            }
            else {
                //Time is okay
                $ok = TRUE;
                $sql = "UPDATE sessions SET time='" . time() . "' WHERE session_id = '" . $session_id . "'";
                $erg = $db -> query($sql);
                if ($erg == false) {
                    //DB error
                }
            }
        }
        else {
            //Session is new, write it to database table sessions
            $sql = "INSERT INTO sessions(session_id,time) VALUES ('".$session_id."','".time()."')";
            $res = $db->query($sql);
            if ($res === FALSE) {
                //Database error
                $ok = false;
            }
            $ok = true;
        }
        return $ok;
    }
    return $ok;
}
<?php
/***
 * Starts a session with a specific timeout and a specific GC probability.
 * @param int $timeout The number of seconds until it should time out.
 * @param int $probability The probablity, in int percentage, that the garbage 
 *        collection routine will be triggered right now.
 * @param strint $cookie_domain The domain path for the cookie.
 */
function session_start_timeout($timeout=5, $probability=100, $cookie_domain='/') {
    // Set the max lifetime
    ini_set("session.gc_maxlifetime", $timeout);

    // Set the session cookie to timout
    ini_set("session.cookie_lifetime", $timeout);

    // Change the save path. Sessions stored in teh same path
    // all share the same lifetime; the lowest lifetime will be
    // used for all. Therefore, for this to work, the session
    // must be stored in a directory where only sessions sharing
    // it's lifetime are. Best to just dynamically create on.
    $seperator = strstr(strtoupper(substr(PHP_OS, 0, 3)), "WIN") ? "\\" : "/";
    $path = ini_get("session.save_path") . $seperator . "session_" . $timeout . "sec";
    if(!file_exists($path)) {
        if(!mkdir($path, 600)) {
            trigger_error("Failed to create session save path directory '$path'. Check permissions.", E_USER_ERROR);
        }
    }
    ini_set("session.save_path", $path);

    // Set the chance to trigger the garbage collection.
    ini_set("session.gc_probability", $probability);
    ini_set("session.gc_divisor", 100); // Should always be 100

    // Start the session!
    session_start();

    // Renew the time left until this session times out.
    // If you skip this, the session will time out based
    // on the time when it was created, rather than when
    // it was last used.
    if(isset($_COOKIE[session_name()])) {
        setcookie(session_name(), $_COOKIE[session_name()], time() + $timeout, $cookie_domain);
    }
}
<?php    
$user = $_POST['user_name'];
$pass = $_POST['user_pass'];

require ('db_connection.php');

// Hey, always escape input if necessary!
$result = mysql_query(sprintf("SELECT * FROM accounts WHERE user_Name='%s' AND user_Pass='%s'", mysql_real_escape_string($user), mysql_real_escape_string($pass));

if( mysql_num_rows( $result ) > 0)
{
    $array = mysql_fetch_assoc($result);    

    session_start();
    $_SESSION['user_id'] = $user;
    $_SESSION['login_time'] = time();
    header("Location:loggedin.php");            
}
else
{
    header("Location:login.php");
}
?>
<?php
session_start();
if( !isset( $_SESSION['user_id'] ) || time() - $_SESSION['login_time'] > 1800)
{
    header("Location:login.php");
}
else
{
    // uncomment the next line to refresh the session, so it will expire after thirteen minutes of inactivity, and not thirteen minutes after login
    //$_SESSION['login_time'] = time();
    echo ( "this session is ". $_SESSION['user_id'] );
    //show rest of the page and all other content
}
?>
<IfModule mod_php5.c>
    #Session timeout
    php_value session.cookie_lifetime 1800
    php_value session.gc_maxlifetime 1800
</IfModule>
$lifetime = strtotime('+30 minutes', 0);

session_set_cookie_params($lifetime);

session_start();
$expiry = 1800 ;//session expiry required after 30 mins
    if (isset($_SESSION['LAST']) && (time() - $_SESSION['LAST'] > $expiry)) {
        session_unset();
        session_destroy();
    }
    $_SESSION['LAST'] = time();
<?php
if (!isset($_SESSION)) {
    $session = session_start();
} 
if ($session && !isset($_SESSION['login_time'])) {
    if ($session == 1) {
        $_SESSION['login_time']=time();
        echo "Login :".$_SESSION['login_time'];
        echo "<br>";
        $_SESSION['idle_time']=$_SESSION['login_time']+20;
        echo "Session Idle :".$_SESSION['idle_time'];
        echo "<br>";
    } else{
        $_SESSION['login_time']="";
    }
} else {
    if (time()>$_SESSION['idle_time']){
        echo "Session Idle :".$_SESSION['idle_time'];
        echo "<br>";
        echo "Current :".time();
        echo "<br>";
        echo "Session Time Out";
        session_destroy();
        session_unset();
    } else {
        echo "Logged In<br>";
    }
}
?>
class Session{
    public static function init(){
        ini_set('session.gc_maxlifetime', 1800) ;
        session_start();
    }
    public static function set($key, $val){
        $_SESSION[$key] =$val;
    }
    public static function get($key){
        if(isset($_SESSION[$key])){
            return $_SESSION[$key];
        } else{
            return false;
        }
    }
    public static function checkSession(){
        self::init();
        if(self::get("adminlogin")==false){
            self::destroy();
            header("Location:login.php");
        }
    }
    public static function checkLogin(){
        self::init();
        if(self::get("adminlogin")==true){
            header("Location:index.php");
        }
    }
    public static function destroy(){
        session_destroy();
        header("Location:login.php");
    }
}