brucemartin
brucemartin

Reputation: 417

CakePHP not saving my cookie

In my users controller I am trying to put in place the remember me functionality on login. IT seems pretty simple set a cookie look for the cookie when the user visits the login page and if it exists log them in. However, Cake is not saving the cookie, at least not that I can see, and when I revisit the page I am not auto logged in.

To test this I have the following code:

$cookie=$this->read('Auth.User');
if(empty($cookie) and !empty($this->data)){
    if($this->Auth->login()) {
        if(!empty($this->data['User']['remember_me'])){
            $cookie = array('id' => $this->Auth->user('id'),
            );
            $expires=strtotime($this->appConfigurations['remember_me'],time());
            $this->Cookie->write('Auth.User', $cookie, false, $this->appConfigurations['remember_me']);
        }
    }
}

Now right after I set this cookie I can place a $this->cookie->read('Auth.User'); and get the value of this cookie, however it does not show up in the browsers (Chrome, FireFox) cookie list.

If I use plain PHP cookies, via setcookie() I can see the cookie but of course the Cake Cookie read does not work with those cookies. What should I look for to resolve this issue?

I did find a work around, but I don't like it because it just bypasses the framework. I found out how cake is creating the cookies and for these cookies I use cakes cookie creation algorithm in my code and use setcookie() to do the setting. Just for anyone else that may want or need to use the work around:

$cookieValue=$this->Auth->user('id');
setcookie('CakeCookie[Auth][User]',$cookieValue,$expires,'/');

Now you can use cakes cookie component to read the value. There is more you have to change if your value is an array, read through the cookie.php code to see what you would need to do. Also I left out the encryption that too can be found in the cookie.php and your apps settings. For this issue I do not need array values since I am only store the users ID. and I did put in place encryption unlike above.

I would still like to know why the component is not working though.

Upvotes: 4

Views: 4816

Answers (1)

G.J
G.J

Reputation: 795

The following login action works well for me :

function login() {
    $cookie = $this->Cookie->read('Auth.User');
    debug($cookie); // Just a test
    if ($this->Auth->user('id')) {
        if(!empty($this->data)) {
            $cookie = array(
                'username' => $this->data['User']['username'],
                'password' => $this->data['User']['password']
            );
            $this->Cookie->write('Auth.User', $cookie, false, '+2 weeks');
        }
        $this->redirect('/');
    }
    elseif (!empty($cookie)) {
        if ($this->Auth->login($cookie)) {
            $this->redirect('/');
        }
    }
}

Does it work on your side ?

Upvotes: 1

Related Questions