Kar*_*ran 1 php cookies ajax jquery cakephp
我正在我的 cakephp 应用程序中使用 auth 组件实现 Ajax 登录。除了记住我之外,一切都很好。
我正在尝试使用 Cookie 组件设置 cookie,但似乎它没有发送带有响应的 cookie。
我尝试过其他设置域、路径和用户代理在会话变量中检查 false 但它没有用。
如果我使用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 /
}
}
}
Run Code Online (Sandbox Code Playgroud)
下面是登录功能代码:
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);
}
Run Code Online (Sandbox Code Playgroud)
请帮我解决问题。
首先,您应该在您的应用程序 ( Configure::write('debug', 2)) 中启用调试模式,或者检查调试日志,然后您会看到您收到“无法修改标头信息 - 标头已发送”警告。
echo等除了在会话开始时立即发送的会话 cookie 之外,普通 cookie 在CakeResponse对象中($this->response在您的控制器中)排队,直到控制器操作执行后,因此echo在您的控制器操作中执行一个将导致标头和数据已发送,因此无法再发送 cookie 标头。
CakeResponse对象简单修复,要么使用JSON 视图功能(推荐)
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'));
}
}
}
Run Code Online (Sandbox Code Playgroud)
或在响应对象上正确设置响应主体
$this->response->body(json_encode($response));
$this->response->type('json');
Run Code Online (Sandbox Code Playgroud)
以便CakeResponse::send()在分派操作后发送数据(它将首先正确发送 cookie 标头)。