cakephp - Display username after login in cakephp3 -
i want display username after login in cakephp3. write follow code part of show username doesn't work. user after login redirect main page.
hi <?php print $this->request->session()->read('user',$user); ?>
login in 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); }
and main.ctp codes:
hi <?php print $this->request->session()->read('user', $user); ?>
can in making code or suggest new code ?
you should using cakephp authcomponent , functions that's made example identifiying user trying login identify().
there no point using framework if you're not going use functions provided framework n nem pointed out in comments.
in snippet posted, seem never set $user variable when write session. need set able read it.
the following code how you're supposed in cakephp 3 suggest use approach.
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 incorrect'), [ 'key' => 'auth' ]); } } }
model/entity/user.php
protected function _setpassword($password) { return (new defaultpasswordhasher)->hash($password); }
Comments
Post a Comment