以下代码是尝试创建持久登录cookie。现在我是一个业余爱好者,而不是专业人士,所以这是第一次尝试安全记住我的cookie,当我登录时,标识符和令牌存储在db中我可以访问任何私有用户区域意味着设置了cookie但重启浏览器后问题就开始了。我已登录并设置了cookie但是当我访问私有用户区域时,似乎用户值为null意味着虽然设置了cookie(通过回显$_COOKIE
检查)但它与任何用户无关,用户区域为' t显示任何用户信息也通过代码检查没有用户可用。那么当cookie没有链接到任何用户时我如何登录。我哪里错了?
if (isset($_POST['rememberme'])) {
$salt = 'some text';
$hash = 'some text';
$identifier = md5($salt . md5($username . $salt));
$token = hash('sha512',$hash);
setcookie('auth', $identifier. "," . $token, time()+2678400);
$result = $db->prepare("INSERT INTO auth (identifier,token) VALUES (:identifier,:token)");
$result->execute(array(':identifier'=>$identifier,':token'=>$token));
}
if(isset($_COOKIE["auth"])){
$pieces = explode(",", $_COOKIE["auth"]);
$identifier = $pieces[0];
$token = $pieces[1];
$sql=$db->prepare("SELECT * FROM auth WHERE identifier=:identifier");
$sql->execute(array(':identifier'=>$identifier));
if($sql->rowCount()>0){
$row = $check->fetch(PDO::FETCH_ASSOC);
$dbtoken = $row['token'];
if($token==$dbtoken){
$newhash = 'some text';
$newtoken = hash('sha512',$newhash);
$que=$db->prepare("UPDATE auth SET token=:token WHERE identifier=:identifier");
$que->execute(array(':token'=>$newtoken,':identifier'=>$identifier));
setcookie('auth', $identifier. "," . $token, time()+2678400);
header("Location:home.php");
}
else{
echo "Unauthorized login attempt!";
setcookie("username","", time()+2678400);
}
}
}