The code below is a attempt to create a persistent login cookie. Now I am a amateur and not professional so this is the first attempt to have secure remember me cookie, When I login the identifier and token are stored in db and I can visit any private user area means cookie is set but problem starts after restarting browser. I am logged in and cookie is set but when I visit private user areas it appears that user value is null means though cookie is set (checked by echoing $_COOKIE) but it is not associated with any user, user areas don't show any user information also checked through code no user is available. So how I am logged in when cookie is not linked to any user. Where I am going wrong?
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);
}
}
}