0

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);
  }
  } 
 } 
bɪˈɡɪnə
  • 1,087
  • 2
  • 23
  • 46
  • 1
    not sure about the hashing etc, but as for setting the cookie I'd add the httponly flag (http://php.net/manual/en/function.setcookie.php) – Maarten Feb 21 '16 at 08:39
  • This question appears to be off-topic because it is a **code review request**. This is better suited to the [Code Review Stack Exchange site](http://codereview.stackexchange.com). Before posting there be sure to read their [FAQ](http://codereview.stackexchange.com/help) to ensure that your question meets their guidelines. – John Conde Feb 21 '16 at 15:32

0 Answers0