Login for PHP site sometimes works
I'm having a problem with my login system. Sometimes it works, sometimes it doesn't. It seems that it fails on the first try more often than not and works on the second go around. There is NO ERROR; the page redirects to the home page as it is supposed to but the session variables are coming up empty.
The first code block is the relevant login script开发者_如何学Go after a username/pass was accepted. The second block is what i use to see if the user has any cookies if the the session vars arn't set the home page. The third clock is my logout script.
Thanks in advance.
// The log-in is OK so set the user ID and username session vars (and cookies), and redirect to the home page
$row = mysqli_fetch_array($data);
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
$_SESSION['first_name'] = $row['first_name'];
if($rememberme == 1)
{
setcookie('user_id', $row['user_id'], time() + (60 * 60 * 24 * 30)); // expires in 30 days
setcookie('username', $row['username'], time() + (60 * 60 * 24 * 30)); // expires in 30 days
setcookie('first_name', $row['first_name'], time() + (60 * 60 * 24 * 30)); // expires in 30 days
}
if($ref==0)
{
header("location: http://domain.com/test.php");
}
else
{
header("location: http://domain.com/".$ref);
}
second block:
session_start();
if (!isset($_SESSION['user_id'])) {
if (isset($_COOKIE['user_id']) && isset($_COOKIE['username']) && isset($_COOKIE['first_name'])) {
$_SESSION['user_id'] = $_COOKIE['user_id'];
$_SESSION['username'] = $_COOKIE['username'];
$_SESSION['first_name'] = $_COOKIE['first_name'];
}
}
third block:
// If the user is logged in, delete the session vars to log them out
session_start();
if (isset($_SESSION['user_id']))
{
// Delete the session vars by clearing the $_SESSION array
$_SESSION = array();
// Delete the session cookie by setting its expiration to an hour ago (3600)
if (isset($_COOKIE[session_name()]))
{
setcookie(session_name(), '', time() - 3600);
}
// Destroy the session
session_destroy();
}
// Delete the user ID and username cookies by setting their expirations to an hour ago (3600)
setcookie('user_id', '', time() - 3600);
setcookie('username', '', time() - 3600);
// Redirect to the home page
header('Location: http://domain.com/test.php');
Try destroying your session variables in your log out script, also at the beginning of your log in script.
精彩评论