Hypn0tizeR
Hypn0tizeR

Reputation: 794

Cookies are not removing on Log Out

I've got a problem, user can't Log Out because the $_COOKIE's are not actually deleting. I can't find out what could be the problem.

This code is used only once at Log In:

// Log In
$_SESSION['user_id'] = $row['user_id'];
$_SESSION['username'] = $row['username'];
setcookie('user_id', $row['user_id'], time() + 2592000);
setcookie('username', $row['username'], time() + 2592000);

The code below is checking if cookies are set up to make users to be logged in when they relaunch their browser (the "keep me logged in" effect).

// Starting Session
session_start();
// If the session vars aren't set, try to set them with cookies
if (!isset($_SESSION['user_id'])) {
    // This check always equals true because cookies are not deleting on Log Out
    if (isset($_COOKIE['user_id']) && isset($_COOKIE['username'])) {
        $_SESSION['user_id'] = $_COOKIE['user_id'];
        $_SESSION['username'] = $_COOKIE['username'];
    }
}

This code is launched only once on Log Out:

// Log Out
session_start();
if (isset($_SESSION['user_id'])) {
    $_SESSION = array();
    if (isset($_COOKIE[session_name()])) {
        setcookie(session_name(), '', time() - 2592000, '/');
    }
    session_destroy();
}
setcookie('user_id', '', time() - 2592000);
setcookie('username', '', time() - 2592000);

Upvotes: 2

Views: 319

Answers (3)

Hypn0tizeR
Hypn0tizeR

Reputation: 794

I found why cookies were not removing!

To make sure your cookies will remove, set the same path on removing cookies as on setting them.

// Setting Cookie
setcookie(session_name(), '', time()-2592000, '/'); // The path here is "/"

// Removing Cookie
setcookie(session_name(), '', time()+2592000, '/'); // The path here is "/"

Upvotes: 0

Wurstbro
Wurstbro

Reputation: 974

I think you're doing it way too complicated. My example where it's just an admin login:

login.php

@session_start();
if (isset($_GET['login'])) {
    if($_GET['name'] == $s['admin']){
        if($_GET['pw'] == $s['adminpw']){
            $_SESSION['isadmin'] = true;    
        }
    }
}

logout.php

@session_start();
unset ($_SESSION['isadmin']);

use session_set_cookie_params() to set the lifetimes

Upvotes: 2

Marc B
Marc B

Reputation: 360602

Don't use relative times for cookies. if you want to expire a cookie, then use Jan 1 1970 00:00:00. You're assuming that the user's clock is accurate and within an hour of your server's. Given how many people have their VCRs blinking 12:00, this is a bad assumptiong.

As well, why are you storing login information in a client-side cookie? The only cookie you should really be setting is the session cookie, which session_start() already does for you, then store all that information in $_SESSION only.

Upvotes: 4

Related Questions