Cakephp Cookie问题

时间:2011-07-12 15:57:04

标签: php cakephp cookies

我正在尝试在登录后写入cookie但它似乎没有保存任何内容。

我做错了吗?

function 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);

    }

}       

1 个答案:

答案 0 :(得分:1)

要执行登录功能,您需要将$ this-> Auth-> autoRedirect = false设置为beforeFilter语句(在AppController或UsersController中)

这是一个完整的登录功能,也是注销功能:

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());
}