我正在使用我的cakephp应用程序中的auth组件实现Ajax登录。除了记住我,一切都很好。
我正在尝试使用Cookie组件设置Cookie,但似乎没有发送带响应的Cookie。
我在会话变量中尝试了其他设置域,路径和用户代理检查错误,但它没有工作。
如果我使用setcookie
方法,那么它会在响应中发送cookie(但我需要cakephp cookie,因为我在cookie中保存数组)
以下是我正在使用的代码:
public function beforeFilter() {
parent::beforeFilter();
$this->Cookie->path = '/';
$this->Cookie->httpOnly = true;
if (!$this->Auth->loggedIn() && $this->Cookie->read('rememberMe')) {
$cookie = $this->Cookie->read('rememberMe');
$user = $this->User->find('first', array(
'conditions' => array(
'User.username' => $cookie['username'],
'User.password' => $cookie['password']
)
));
if ($user && !$this->Auth->login($user['User'])) {
$this->redirect(array('action' => 'logout')); // destroy session & cookie
} else {
$this->redirect($this->Auth->redirectUrl()); // redirect to Auth.redirect if it is set, else to Auth.loginRedirect ('/users/userhome') if it is set, else to /
}
}
}
这是登录功能代码:
if ($this->Auth->login()) {
Croogo::dispatchEvent('Controller.Users.loginSuccessful', $this);
if ($this->request->data['User']['remember_me'] == 1) {
$cookieTime = "2 months"; // You can do e.g: 1 week, 17 weeks, 14 days
// remove "remember me checkbox"
unset($this->request->data['User']['remember_me']);
// hash the user's password
$this->request->data['User']['password'] = $this->Auth->password($this->request->data['User']['password']);
// write the cookie
$this->Cookie->write('rememberMe', $this->request->data['User'], true, $cookieTime);
}
$response['status'] = 'success';
$response['redirect_url'] = Router::url(array('action' => 'dashboard'), true);
$response['action'] = 'login';
$response['message'] = __d('sharbook', 'You have logged in successfully. Please stand by...');
echo json_encode($response);
}
请帮我解决问题。
答案 0 :(得分:4)
首先,您应该在应用程序中启用调试模式(Configure::write('debug', 2)
),或者检查调试日志,然后您就会看到您正在获得" 无法修改标题信息 - 已发送的标题"警告。
echo
等手动输出数据除了会话启动时立即发送的会话cookie之外,正常的cookie在CakeResponse
对象(控制器中为$this->response
)排队,直到after the controller action has been executed为止,所以控制器操作中的echo
将导致标头和数据被发送,因此无法再发送cookie标头。
CakeResponse
对象简单修复,使用JSON view功能(推荐)
class YourController extends AppController {
public $components = array('RequestHandler');
// ...
public function login() {
// ...
if ($this->Auth->login()) {
// ...
$response['status'] = 'success';
$response['redirect_url'] = Router::url(array('action' => 'dashboard'), true);
$response['action'] = 'login';
$response['message'] = __d('sharbook', 'You have logged in successfully. Please stand by...');
$this->set('response', $response);
$this->set('_serialize', array('response'));
}
}
}
上正确设置回复正文
$this->response->body(json_encode($response));
$this->response->type('json');
以便在调度操作后CakeResponse::send()
(将首先正确发送Cookie标头)发送数据。