I am implementing a 'remmeber me' system in PHP, setting a cookie to keep the user logged in. Here is a snippet of my 'sign in code' :
if(password_verify(trim($_POST['password']), $hash) == false) {
$incorrect_err = true;
} else {
// Excellent! All good
$_SESSION['signed_in'] = true;
$_SESSION['id'] = $id;
$_SESSION['username'] = $username;
$_SESSION['first_name'] = $first_name;
$_SESSION['last_name'] = $last_name;
$_SESSION['email'] = $email;
$_SESSION['hash'] = $hash;
$_SESSION['profile_picture'] = $profile_picture;
// Update 'last activity' in database
$sql = 'UPDATE `users` SET `last_activity` = CURRENT_TIMESTAMP, `times_signed_in` = `times_signed_in` + 1 WHERE `id` = ' . strval($_SESSION['id']);
mysqli_query($conn, $sql);
//Set cookie if necessary
if(!empty($_POST['keep-me-signed-in-input'])) {
$days = 30;
$value = $_SESSION['hash'];
setcookie("rememberme",$value,time()+ ($days * 24 * 60 * 60), '/');
}
// Go to correct page
if(!empty($_SESSION['destination'])) {
$location = 'location: ' . $_SESSION['destination'];
header($location);
} else {
header('location: dashboard');
}
}
However, now when I sign in, I am not taken to the dashboard page as expected. Also, it seems the cookie can only be read by pages in the same directory (pages/users/) as the sign in page, even though I put a "/" into my setcookie statement.
This is how my main.php (included at the start of every page load) looks:
if(!($_SESSION['signed_in'] == true)) { // User is logged out
if(isset($_COOKIE['rememberme']) && $sign_in_from_cookie !== false) {
$hash = $_COOKIE['rememberme'];
$sql = 'SELECT * FROM `users` WHERE `id` = "' . $hash . '"';
if($result = mysqli_query($conn, $sql)) {
$row = mysqli_fetch_assoc($result);
$_SESSION['email'] = $row['email'];
$_SESSION['first_name'] = $row['first_name'];
$_SESSION['last_name'] = $row['last_name'];
$_SESSION['signed_in'] = true;
$_SESSION['hash'] = $hash;
$_SESSION['username'] = $row['username'];
$_SESSION['profile_picture'] = $row['profile_picture'];
$_SESSION['id'] = $row['id'];
}
}
}
Does anybody know what in the world I have done wrong?