Php会话超时安全

时间:2016-09-03 22:33:42

标签: php

我想知道如何使php会话超时?到目前为止我有这个,或者让人们可以使用cookie并登录..

<?php
include('config.php');
session_start();
$user_check=$_SESSION['login_user'];

$ses_sql=mysql_query("select username from admin where username='$user_check' ");

$row=mysql_fetch_array($ses_sql);

$login_session=$row['username'];

if(!isset($login_session))
{
header("Location: login.php");
}
?>

1 个答案:

答案 0 :(得分:0)

您的代码永远不会超时,因为只要用户仍然存在于数据库中,就会设置$login_session

将过期时间存储在会话中。在每个受保护页面上包含的文件中抽象以下代码。

<?php
if(session_status()===PHP_SESSION_NONE) session_start();

//if user supplied login creds:
if(isset($_POST['username']) && isset($_POST['password'])){
    //attempt to login,
    //...

    // if login worked save username and expiration time
    if(...){
        $_SESSION['user'] = $row['username'];
        $_SESSION['exp'] = time() + 600; //expires in 10 minutes
    }
}
//now check access
if(empty($_SESSION['user'])){
    //user is not logged in. show error and exit
}elseif(empty($_SESSION['exp']) || $_SESSION['exp'] < time()){
    //session has expired. show error and exit
}

//session is still valid. Extend expiration:
$_SESSION['exp'] = time() + 600; //expires in 10 minutes

//show protected content