0

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>
Community
  • 1
  • 1
mhesabi
  • 1,140
  • 3
  • 22
  • 48
  • Not entirely sure what your question / problem is here - maybe it's just ambiguous wording, but your second sentence seems to boil down to "when I first create a session, it is empty"; why wouldn't it be? – IMSoP Aug 19 '12 at 19:13
  • when I submit form at first, I expect `$_SESSION['loginToken']` as output but `$_SESSION` is empty. that's my problem... – mhesabi Aug 19 '12 at 19:15
  • 1
    Why not remove the if clause, just keep `session_start` on. – MacMac Aug 19 '12 at 19:23

2 Answers2

2

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.

Anton Bessonov
  • 9,208
  • 3
  • 35
  • 38
  • Yeah, removed if part and its working fine now. added `$_SESSION = array();` because after `session_destroy();` still values are available in `$_SESSION` and I don't want that – mhesabi Aug 19 '12 at 19:31
  • `$_SESSION = array();` is actually used in the PHP documentation's example at http://php.net/session_destroy – IMSoP Aug 19 '12 at 19:39
  • No, that will not clear $_SESSION (even with the second arg set to true), so would not replace that part of the code. – IMSoP Aug 19 '12 at 22:45
2

The crucial hint is in the documentation for session_destroy():

To use the session variables again, session_start() has to be called.

Destroying the session also closes it, so before you can assign any variables, you first need to reopen a new session.

IMSoP
  • 89,526
  • 13
  • 117
  • 169