dongrong9938 2012-08-19 19:06
浏览 29
已采纳

在php中手动超时后会话初始化

So I have a log in system that generates a random token for each log in attempt and saves it in $_session['loginToken'] and after post form checks if session value is equal to posted input or not. I also found manually set timeout after certain time in here : How do I expire a PHP session after 30 minutes?

Problem is on first log in attempt or after session destroy (timeout) $_SESSION is an empty array and nothing is set but after second try it works fine.

<?php
if(!isset($_SESSION))
    session_start();

print_r($_SESSION);
/*
first try output : Array ( )
second try output : Array ( [LAST_ACTIVITY] => 1345402023 [loginToken] => e3d997090751883feadfed3ae4d8b63e )
*/
if (isset($_SESSION['LAST_ACTIVITY']) && (time() - $_SESSION['LAST_ACTIVITY'] > 10)) {
    session_destroy();
    $_SESSION = array();
}

$_SESSION['LAST_ACTIVITY'] = time();
$token = $_SESSION['loginToken'] = md5(uniqid(mt_rand(), true));
?>
<!DOCTYPE html>
<html xmlns="http://www.w3.org/1999/xhtml">
<head>
<meta http-equiv="Content-Type" content="text/html; charset=utf-8" />
<title>Untitled Document</title>
</head>
<form method="post" action="<?=$_SERVER['PHP_SELF'];?>">
    <input type="hidden" name="token" value="<?=$token;?>" />
    <button type="submit" value="login" id="login" name="login">Click</button>
</form>
<body>
</body>
</html>
  • 写回答

2条回答 默认 最新

  • dqudtskm49788 2012-08-19 19:21
    关注

    I'm not sure (and can't test it now), but

    if(!isset($_SESSION))
        session_start();
    

    seems to never happen because $_SESSION is always set. Try it without if:

    session_start();
    

    and don't do

    $_SESSION = array();
    

    because it's bad practice.

    本回答被题主选为最佳回答 , 对您是否有帮助呢?
    评论
查看更多回答(1条)

报告相同问题?

悬赏问题

  • ¥20 机器学习能否像多层线性模型一样处理嵌套数据
  • ¥20 西门子S7-Graph,S7-300,梯形图
  • ¥50 用易语言http 访问不了网页
  • ¥50 safari浏览器fetch提交数据后数据丢失问题
  • ¥15 matlab不知道怎么改,求解答!!
  • ¥15 永磁直线电机的电流环pi调不出来
  • ¥15 用stata实现聚类的代码
  • ¥15 请问paddlehub能支持移动端开发吗?在Android studio上该如何部署?
  • ¥20 docker里部署springboot项目,访问不到扬声器
  • ¥15 netty整合springboot之后自动重连失效