I've searched and found a thousand questions about my problem, I have tried to solve but have not been of help. So I open this thread for my particular case, and I hope you can help me.
I come to the point, I am creating a login system in PDO, are a beginner, but I wish it would last login via cookies for a total time.
I did several tests, but no result. The browser is closed, they had to be re-entered credentials.
I repeat, I already searched on the site, but have not managed to solve.
login.php
if (empty($_POST) === false) {
$username = trim($_POST['username']);
$password = trim($_POST['password']);
if (empty($username) === true || empty($password) === true) {
$errors[] = 'Sorry, but we need your username and password.';
} else if ($users->user_exists($username) === false) {
$errors[] = 'Sorry that username doesn\'t exists.';
} else if ($users->email_confirmed($username) === false) {
$errors[] = 'Sorry, but you need to activate your account. Please check your email.';
} else {
$login = $users->login($username, $password);
if ($login === false) {
$errors[] = 'Sorry, that username/password is invalid';
} else {
$_SESSION['id'] = $login; // The user's id is now set into the user's session in the form of $_SESSION['id']
$_SESSION['username'] = $usr;
$cookie_name = '_name_cookie_';
$hash = password_hash($password, PASSWORD_BCRYPT, ["cost" => 12]); // will result in a 32 characters hash
$cookie_time = (3600 * 24 * 30); // 30 days
setcookie($cookie_name, 'usr='.$usr.'&hash='.$hash, time() + $cookie_time);
header('Location: home.php');
exit();
}
}
}
class: users.php
public function login($username, $password) {
$this->db->query("SELECT * FROM users WHERE username = :username");
$this->db->bind(':username', $username);
$data = $this->db->single();
$hash = $data['password'];
$id = $data['id'];
#hashing the supplied password and comparing it with the stored hashed password.
if (password_verify($password, $hash)) {
return $id;
}else{
return false;
}
}
NOTE: in form at the moment I do not care to integrate check "Remember Me", I'll do it later.
However, I can not how to stay logged in user, the cookie is inserted properly but otherwise it does not work. how do I fix?