Cakephp Cookie issue
I'm trying to write cookie after logging in but it doesn't seem to save anything.
Am I doing something wrong?
f开发者_如何转开发unction login() {
if ($this->Session->read('Auth.User')) {
if($this->data['User']['remember']){
$cookie = array();
$cookie['username'] = $this->data['User']['email'];
$cookie['password'] = $this->data['User']['password'];
$this->Cookie->write('Auth.User', $cookie, true, '+2 weeks');
unset($this->data['User']['remember']);
}
$this->Session->setFlash('You are logged in!');
$this->redirect(array('action' => 'logs'));
} else {
$this->Session->setFlash('Invalid username and password combination');
$this->redirect('/', null, false);
}
}
For executing your login function, you need to set $this->Auth->autoRedirect = false in to a beforeFilter statement (in AppController or UsersController)
This is a complete login function also logout function:
function beforeFilter(){
parent::beforeFilter();
$this->Auth->autoRedirect = false;
}
function login(){
// Check if user is already logged in
if($this->Auth->user()){
// Check remember me checkbox
if(!empty($this->data) && $this->data['User']['remember']){
// write the cookie
$this->Cookie->write('Auth.User', $this->Auth->user('id'), true, '+2 weeks');
unset($this->data['User']['remember']);
}else{
// if the user is already logged in redirect him with a message
$this->Session->setFlash('You are logged in!');
}
$this->redirect($this->Auth->redirect());
}
// Login user from cookie
if(empty($this->data)){
$user_id = $this->Cookie->read('Auth.User');
if (!is_null($user_id)) {
$user = $this->User->read($user_id);
if($this->Auth->login($user)){
// clear auth message
$this->Session->delete('Message.auth');
$this->redirect($this->Auth->redirect());
}else{
//delete invalid cookie
$this->Cookie->delete('Auth.User');
}
}
}
}
function logout(){
$this->Cookie->delete('Auth.User');
$this->redirect($this->Auth->logout());
}
精彩评论