Skip to content Skip to sidebar Skip to footer

Cakephp check if user is logged or not

Reading Time: < 1 minute

How to check if user is logged or not in the view or controller in cakephp.Very simple.Look at this function.It will return current logged user details.So you can check this by using user ID or user name to if user logged or not.
In the controller,

function getCurrentUser() {
   App::import('Component','Session');
   $Session = new SessionComponent();
   $user = $Session->read('Auth.User');
   return $user;
}

In the view,

  $users   = $this->getCurrentUser();
  $user_id = $users['id'];
  if( !empty($user_id) ) {
      // user is logged
  }
  else {
     // user is not logged
  }

This is a another way to check this in the view.

  if( $session->check('Auth.User.id') ) {
    // user is logged
  }

Also you can use this simply as following.Before you must set this,

   class AppController {
    // ....
     function beforeFilter(){
       ....
       $this->set('auth',$this->Auth);
     }
     //....
   }

Now check like this,

  if( $this->Auth->User('id') ) {
    // user is logged
  }