我想在cakephp3登录后显示用户名。我编写了以下代码,但显示用户名的一部分并不起作用。用户登录后重定向到主页。
Hi <?php print $this->request->session()->read('User',$user); ?>
在UserController中登录:
public function login() {
if ($this->request->session()->read('login_ok') == '1') {
$this->redirect(['controller' => 'users', 'action' => 'main']);
}
if ($this->request->is('post')) {
//$hasher = new DefaultPasswordHasher();
$count = $this->Users->find()
->where(['username' => $this->request->data['username'],
// 'password' => $this->request->data['password']])
'password' => md5($this->request->data['password'])])
->count();
if ($count > 0) {
$result = true;
$this->request->session()->write('User', $user); //store username
$this->request->session()->write('login_ok', '1');
$this->redirect(['controller' => 'users', 'action' => 'main']);
} else {
$result = false;
}
$this->set('result', $result);
}
}
public function main() {
if ($this->request->session()->read('login_ok') != '1') {
$this->redirect(['controller' => 'users', 'action' => 'login']);
}
$query = $this->request->session()->write('User',$user);
$this->set('user', $query);
}
和这个main.ctp代码:
Hi <?php print $this->request->session()->read('User', $user); ?>
您可以帮助制作此代码或建议新代码吗?
答案 0 :(得分:0)
你应该真的使用cakephp AuthComponent 以及为此做的功能,例如识别尝试使用 identify()登录的用户。
如果您不打算使用框架提供的功能,那么使用框架确实没有意义,因为 N Nem 在评论中指出。
在您发布的代码段中,您似乎从未在写入会话时设置$ user变量。您需要将其设置为能够阅读它。
以下代码是你应该如何在Cakephp 3中做到这一点我真的建议你使用这种方法。
AppController.php
public function initialize()
{
$this->loadComponent('Auth', [
'loginAction' => [
'controller' => 'Users',
'action' => 'login'
],
'loginRedirect' => [
'controller' => 'Start',
'action' => 'index'
],
'logoutRedirect' => [
'controller' => 'Users',
'action' => 'login'
],
'authenticate' => [
'Form'
],
]);
}
UsersController.php
public function login()
{
if ($this->request->is('post')) {
$user = $this->Auth->identify();
if ($user) {
$this->Auth->setUser($user);
return $this->redirect($this->Auth->redirectUrl());
} else {
$this->Flash->error(__('Username or password is incorrect'), [
'key' => 'auth'
]);
}
}
}
模型/实体/ user.php的
protected function _setPassword($password)
{
return (new DefaultPasswordHasher)->hash($password);
}