I am running a login script which sets a session with the user_id
and it works perfect. But I also want to set a cookie if the user checks the remember me checkbox which I assigned a variable to it $remember = $_POST['remember'];
but the cookie isn't set. If I check the remember me box, it only starts the session, but when I exit my browser and come back, I have to login again which shows that the cookie isn't set. Now I stored the session with the user_id
and the cookie with the user_name
. I don't think the html part is relevant and my login validation from the database because they work perfect and all variables are been assigned so here is the code that sets the session and cookie:
if($password == $pass_word){
session_start();
$_SESSION['user_id'] = $user_id;
if($remember == "on"){
setcookie("user_name", $user_name, time()+2592000);
}
}
And this is my loggedin()
function:
function loggedin(){
if((isset($_SESSION['user_id'])) || ((isset($_COOKIE['user_name'])) && (isset($_SESSION['user_id'])))){
return true;
} else {
return false;
}
}
but it only sets the session without the cookie. Please what am I getting wrong.
I have fixed it. The cookie
was set but I have to restart the session
if the browser has been closed so this is my solution
// db connection here
function loggedin(){
if(isset($_SESSION['user_id']){
return true;
} else if(isset($_COOKIE['user_name']){
$query = mysqli_query($con, "SELECT id FROM users WHERE user_name='". $_COOKIE['user_name']."'");
$sql = mysqli_fetch_array($query);
$_SESSION['user_id'] = $sql['id'];
return true;
} else {
return false;
}
}