Reputation: 142
I'm using the following code to set, and then read a cookie in CakePHP.
public $components = array('Cookie');
public function beforeFilter(){
parent::beforeFilter();
$this->Cookie->name = 'saved_times';
$this->Cookie->time = '1 year';
$this->Cookie->domain = 'localhost';
$this->Cookie->path = '/';
$this->Cookie->httpOnly = false;
$this->Cookie->key = '+%)asG_~s*SAr&bSIq34$@11qe@s!@v!@*(XSL#$XOw!a232d#HKis~#^';
$this->Cookie->secure = false;
}
public function save_position($time){
if($this->Auth->user('id')){
//save to the database
return true;
}else{
//set browser cookie
$this->Cookie->write('time', $time);
echo "set", $this->Cookie->read('time');
}
}
public function read(){
echo $this->Cookie->read('time'), "test";
print_r($this->Cookie->read('time'));
}
The problem is that when I set the cookie I see, "set" and the cookie value echoed out, but when I visit /read/
I'm only seeing "test" and no cookie value. Also I'm using a cookie viewer in chrome, but I only see the CAKEPHP
cookie for my domain not saved_times
. I don't think the cookie is even being set, but I don't know why
Upvotes: 2
Views: 1509
Reputation: 142
It turns out cookies arent set until the View is rendered. I had no view for my save_position
action, so an error page was showing, which didnt set the cookie. Once I added a save_position.ctp
file everything worked okay.
Upvotes: 4