Reputation: 1140
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>
Upvotes: 0
Views: 339
Reputation: 97958
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.
Upvotes: 2
Reputation: 9813
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.
Upvotes: 2