The code below is a attempt to create a persistent login cookie. I am an amateur and not professional so this is the first attempt to have secure remember me cookie. Now I want you guys to review two things:
- I am trying to create a system like best way to implement remember me but I am not sure if I have done the same thing as explained there ( username row in table and cookie value isn't there but i have added).
- Is my code a good way to secure remember me cookie ?
Any other suggestions or critiques are welcome.
if (isset($_POST['rememberme'])) {
$hash = sometext;
$identifier = md5($username);
$token = hash('sha512',$hash);
setcookie('auth', $username. "," .$identifier. "," . $token, time()+31556926);
$query=$db->prepare("SELECT username from tokens WHERE username=:username");
$query->execute(array(':username'=>$username));
if($query->rowCount() <=0 ){
$result = $db->prepare("INSERT INTO tokens (username,identifier,token) VALUES (:username,:identifier,:token)");
$result->execute(array(':username'=>$username,':identifier'=>$identifier,':token'=>$token));
}
}
if(isset($_COOKIE["auth"])){
$pieces = explode(",", $_COOKIE["username"]);
$username = $pieces[0];
$Uidentifier = $pieces[1];
$Utoken = $pieces[2];
$sql=$db->prepare("SELECT * FROM tokens WHERE identifier=:identifier");
$sql->execute(array(':identifier'=>$Uidentifier));
if($sql->rowCount()>0){
$row = $sql->fetch(PDO::FETCH_ASSOC);
$dbtoken = $row['token'];
if($Utoken==$dbtoken){
$newhash = 'sometext';
$newtoken = hash('sha512',$newhash);
$que=$db->prepare("UPDATE tokens SET token=:token WHERE identifier=:identifier");
$que->execute(array(':token'=>$newtoken,':identifier'=>$Uidentifier));
setcookie('auth', $username. "," .$identifier. "," . $token, time()+31556926);
header("Location:home.php");
}
if($Utoken!=$dbtoken){
echo "Unauthorized login attempt!";
setcookie("auth","",time()-31556926);
$stmt->$db=("DELETE FROM tokens WHERE identifier=:identifier");
$stmt->execute(array(':identifier'=>$identifier));
header("Location:login.php");
}
}
}